Shiro doGetAuthenticationInfo方法登录后获取不到正确的权限

前提:

        Shiro的认证依赖AuthenticatingRealm里的getAuthenticationInfo方法,该方法会调用我们自定义的认证方法doGetAuthenticationInfo获取本次认证的结果,如下:

   public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
      AuthenticationInfo info = this.getCachedAuthenticationInfo(token);
      if (info == null) {
         info = this.doGetAuthenticationInfo(token); // 这句是调用自定义子类Realm的认证方法
         log.debug("Looked up AuthenticationInfo [{}] from doGetAuthenticationInfo", info);
         if (token != null && info != null) {
            this.cacheAuthenticationInfoIfPossible(token, info);
         }
      } else {
         log.debug("Using cached authentication info [{}] to perform credentials matching.", info);
      }

      if (info != null) {
         this.assertCredentialsMatch(token, info);
      } else {
         log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}].  Returning null.", token);
      }

      return info;
   }

 

问题描述:

        我在用LoginUtil.login自定义认证后,通过isPermitted方法查询权限。发现不管查询的是哪个权限,结果都是存在的。如下的两个println方法输出都是true:

   protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
      throws AuthenticationException
   {
      UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

      try {
         String userName = token.getUsername().trim();
         String passWord = String.valueOf(token.getPassword());
         User user = LoginUtil.login(userName, passWord);
         Subject currentUser = SecurityUtils.getSubject();

         System.out.println(currentUser.isPermitted("server_info:license_manage")); // true
         System.out.println(currentUser.isPermitted("fee_info:fee_list")); // true

         return new SimpleAuthenticationInfo(user.getUserId(), passWord, getName());
      }
      catch(AuthenticationException e) {
         log.info("login failed:" + e.getMessage());
         throw e;
      }
   }

初步分析:

        跟踪isPermitted方法,一直往下看到:

 

        我的系统里,principals为1是admin用户,该测试用户的principals正常应该是3才对。这里的principals为1导致去拿了admin的权限来判断。

 

进一步分析:

        shiro的权限控制在代码的其他地方都是正常生效的,说明这个地方可能还没走完认证过程,导致还不能正常查询。继续往下,doGetAuthenticationInfo方法的返回值是一个SimpleAuthenticationInfo对象,观察该对象的构造函数,发现这个principals是我传递进去的user_id。说明到这才赋值了principals属性,才可以进行权限查询。

   public SimpleAuthenticationInfo(Object principal, Object credentials, String realmName) {
      this.principals = new SimplePrincipalCollection(principal, realmName);
      this.credentials = credentials;
   }

        principals未赋值之前为1,正好对上了系统里admin的user_id,所以误打误撞匹配到了admin的权限。

 

解决办法:

        将权限信息设置到session中这一步,放在我的登录逻辑完成后执行:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值