关于shiro的自定义realms使用过程源码分析

       为了看起来比较简介,我去掉了项目中自定义的登录验证的realm,后面发现使用SecurityUtils.getSubject().getPrincipal()的时候,便永远只能得到登陆时输入的用户名,这个时候需要用户id,但是却不能直接获取,不科学。
        看了之前配置的自定义realm,有两个,一个是登录验证的realm,一个是jdbc的realm,这两个的共同点是都继承了AuthorizingRealm,而 AuthorizingRealm的父类中的doGetAuthenticationInfo是没有定义的,但是在登录subject.login的时候,又会去调用每个realm中的 doGetAuthenticationInfo方法,所以就需要securityManager中配置的realm自已去实现doGetAuthenticationInfo方法,这个方法中主要是用用户名和密码查出用户的信息,然后返回info,保存在shiro的缓存中,查看org.apache.shiro.realm.jdbc.JdbcRealm的源码,方法如下实现:
 
  
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; String username = upToken.getUsername(); ……………………………此处省略一些代码………………………
             //这里验证时就只传了username,所以稍后返回的info中,就只会有用户名,而没有其他信息 info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName()); if (salt != null) { info.setCredentialsSalt(ByteSource.Util.bytes(salt)); } } catch (SQLException e) { ……………………………此处省略一些代码………………………
} finally { JdbcUtils.closeConnection(conn); } return info; }
所以我还是把之前去掉的登录验证realm加回来:
 
 
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token){         ……………………………此处省略一些代码………………………
       //这里传了整个用户的实体类,所以后面返回的info中,就会包含用户名之外的其他信息
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( adminUsersEntity, adminUsersEntity.getPassword(), ByteSource.Util.bytes(adminUsersEntity.getPasswordSalt()), this.getName()); return authenticationInfo; }
那么依据securityManager的配置顺序,到底最后 subject = SecurityUtils.getSubject().getPrincipal()中获取到的到底是哪一个信息?答案是 配置中的 第一个!

格式问题,哎我也是醉了,编辑了老半天的代码区域,发出来就成这样了。就这样把,当记笔记了……

 
 

猜你喜欢

转载自blog.csdn.net/u012602046/article/details/80383553
今日推荐