public class UserRealm extends AuthorizingRealm {
private UserService userService = new UserServiceImpl();
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String username = (String)principals.getPrimaryPrincipal();
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
authorizationInfo.setRoles(userService.findRoles(username));
authorizationInfo.setStringPermissions(userService.findPermissions(username));
return authorizationInfo;
}
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String)token.getPrincipal();
User user = userService.findByUsername(username);
if(user == null) {
throw new UnknownAccountException();//没找到帐号
}
if(Boolean.TRUE.equals(user.getLocked())) {
throw new LockedAccountException(); //帐号锁定
}
//交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以在此判断或自定义实现
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
user.getUsername(), //用户名
user.getPassword(), //密码
ByteSource.Util.bytes(user.getCredentialsSalt()),//salt=username+salt
getName() //realm name
);
return authenticationInfo;
}
}

1、UserRealm父类AuthorizingRealm将获取Subject相关信息分成两步:获取身份验证信息(doGetAuthenticationInfo)及授权信息(doGetAuthorizationInfo);

2、doGetAuthenticationInfo获取身份验证相关信息:首先根据传入的用户名获取User信息;然后如果user为空,那么抛出没找到帐号异常UnknownAccountException;如果user找到但锁定了抛出锁定异常LockedAccountException;最后生成AuthenticationInfo信息,交给间接父类AuthenticatingRealm使用CredentialsMatcher进行判断密码是否匹配,如果不匹配将抛出密码错误异常IncorrectCredentialsException;另外如果密码重试此处太多将抛出超出重试次数异常ExcessiveAttemptsException;在组装SimpleAuthenticationInfo信息时,需要传入:身份信息(用户名)、凭据(密文密码)、盐(username+salt),CredentialsMatcher使用盐加密传入的明文密码和此处的密文密码进行匹配。

3、doGetAuthorizationInfo获取授权信息:PrincipalCollection是一个身份集合,因为我们现在就一个Realm,所以直接调用getPrimaryPrincipal得到之前传入的用户名即可;然后根据用户名调用UserService接口获取角色及权限信息。

最新文章

  1. java中文文档官方下载
  2. 安装phpredisadmin linux nginx服务器下
  3. UIRefreshControl自动刷新
  4. 技术英文单词贴--S
  5. JQuery笔记:JQuery和JavaScript的联系与区别
  6. 组合索引leaf 数据存储
  7. Struts2的模型驱动
  8. 利用模板template动态渲染jsp页面
  9. HDU_4883
  10. Shell执行*.sql
  11. vim编辑器详解(week1_day3)--技术流ken
  12. eregi
  13. [SDOI2013]森林 (启发式合并)
  14. pandas数据结构之series操作
  15. 支付宝sdk集成过程中报 openssl/asn1.h file not found错误的解决办法
  16. MVC常用特性使用
  17. shiro双realm验证
  18. iOS 10 的一个重要更新-新的通知推送 API
  19. English trip -- Review Unit1 Personal Information 个人信息
  20. 【PTA 天梯赛】L3-003 社交集群(并查集)

热门文章

  1. 架构师小跟班:SSL证书免费申请及部署,解决页面样式错乱问题完整攻略
  2. 线程锁,threadinglocal,线程池,生产者消费者模型
  3. Scrapy框架安装失败解决办法
  4. 【Android Studio】使用 Genymotion 调试出现错误 INSTALL_FAILED_CPU_ABI_INCOMPATI
  5. EM算法和高斯混合模型GMM介绍
  6. Js 基础知识1
  7. 保存MTLAB图片是想去掉白边
  8. memCached的配置文件 配置
  9. Intent 常用方法总结
  10. java8(一)Lambda表达式