自定义Realm进行鉴权

1.创建一个Realm类

创建一个类,继承AuthorizingRealm ,然后在doGetAuthenticationInfo中重写认证的方法

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
   String username = (String) token.getPrincipal();
   String password = new String((char[]) token.getCredentials());
   CbUserDO userDO = cbUserService.getUser( username );
   // 账号不存在
   if (userDO==null){
      throw new UnknownAccountException("未找到账号");
   }
   // 密码错误
   if (!password.equals(userDO.getPassword())) {
      throw new IncorrectCredentialsException("账号或密码不正确");
   }
   // 账号锁定
   if (userDO.getStatus() == 0) {
      throw new LockedAccountException("账号已被锁定,请联系管理员");
   }
   // password 需要和 token.getCredentials() 一致且不可为空,不然会抛出异常
   return new SimpleAuthenticationInfo(userDO, password, getName());
}

2.其他需要重写的方法

/**
 * 判断此Realm是否支持此Token
 *
 * @param token tocken
 * @return 是否支持
 */
@Override
public boolean supports(AuthenticationToken token) {
   return token instanceof UsernamePasswordToken;
}

/**
* 该realm的名字
* @return name
*/
@Override
public String getName() {
    return "UserRealm";
}

 /**
 * 授权信息
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    return null;
}

3.需要注意的事项

new SimpleAuthenticationInfo() 中的 password 需要和 token.getCredentials() 的值一致且不可为null,不然会抛出异常

转载于:https://my.oschina.net/u/2555967/blog/2961816

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值