建立一個類,繼承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()); }
/** * 判斷此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; }
new SimpleAuthenticationInfo()
中的 password
須要和 token.getCredentials()
的值一致且不可爲null
,否則會拋出異常ide