自定义Realm进行鉴权

1.建立一个Realm类

建立一个类,继承AuthorizingRealm ,而后在doGetAuthenticationInfo中重写认证的方法java

@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,否则会抛出异常ide

相关文章
相关标签/搜索