美文网首页
shiro--授权--javase

shiro--授权--javase

作者: 李霖神谷 | 来源:发表于2020-01-08 22:26 被阅读0次
    import com.sun.org.apache.bcel.internal.util.ClassPath;
    import org.apache.shiro.SecurityUtils;
    import org.apache.shiro.authc.AuthenticationException;
    import org.apache.shiro.authc.UsernamePasswordToken;
    import org.apache.shiro.config.IniFactorySupport;
    import org.apache.shiro.config.IniSecurityManagerFactory;
    import org.apache.shiro.mgt.SecurityManager;
    import org.apache.shiro.subject.Subject;
    import org.apache.shiro.util.Factory;
    
    public class myshiro {
        public static void main(String[] args) {
    //        创建安全管理器工厂
            Factory<SecurityManager> securityManagerFactory=new IniSecurityManagerFactory("classpath:shiro.ini");
    //        创建安全管理器
            SecurityManager securityManager=securityManagerFactory.getInstance();
    //        设置为当前运行环境
            SecurityUtils.setSecurityManager(securityManager);
    //        创建subject主体
            Subject subject= SecurityUtils.getSubject();
    //        提交认证前创建令牌
            UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken("zhangsan","1234");
    //        提交认证
            try {
                subject.login(usernamePasswordToken);
                boolean boo=subject.hasRole("role1");
                if (boo){
                    System.out.println("它是老大");
                }
                if(subject.isPermitted("user:add")){
                    System.out.println("它有展示的权利");
                }
                if (subject.isAuthenticated()){
                    System.out.println("ok");
                }else{
                    System.out.println("no");
                }
            } catch (AuthenticationException e) {
                e.printStackTrace();
            }
        }
    }
    [users]
    zhangsan=1234,role1,role2
    
    
    [roles]
    role1=user:update,user:add
    role2=user:list
    

    //自定义realm授权,当你在自定义中的realm中有认证的时候就不需要在ini配置文件中在此配置

     //获取授权信息
        @Override
    
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            String  userName=principalCollection.getPrimaryPrincipal().toString();
            List<String> permission=new ArrayList<String>();
            permission.add("user:add");
            permission.add("user:list");
            permission.add("user:update");
            SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
            for (String s : permission) {
                info.addStringPermission(s);
            }
            return  info;
        }
    
    }
    [main]
    userRealm=UserRealm
    securityManager.realm=$userRealm
    

    相关文章

      网友评论

          本文标题:shiro--授权--javase

          本文链接:https://www.haomeiwen.com/subject/dqreactx.html