抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

在SimpleAuthenticationInfo构造函数中,第一个参数是principal,第二个参数是credencials,第三个参数可选,是用于哈希的盐的值,第四个是realm名字。

doGetAuthenticationInfo(AuthenticationToken token)得到AuthticationInfo之后,会自定对比里面的credencitals和subject.login时候传入的credentials是否匹配。匹配就通过,不匹配就会报IncorrectCredentialsException。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
    /**
* 认证
* 这一步我们根据token给的用户名,去数据库查出加密过用户密码,然后把加密后的密码和盐值一起发给shiro,让它做比对
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken userpasswordToken = (UsernamePasswordToken) token;
String username = userpasswordToken.getUsername();
UserDto user = userService.getUserInfo(username);
if (user == null)
throw new AuthenticationException("用户不存在!");
return new SimpleAuthenticationInfo(user, user.getEncryptPwd(), "dbRealm");
// return new SimpleAuthenticationInfo(user, user.getEncryptPwd(), ByteSource.Util.bytes(encryptSalt), "dbRealm");
}

// 授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//返回实体
SimpleAuthorizationInfo result = new SimpleAuthorizationInfo();
Set<String> roles = new HashSet<>();
roles.add("user");
result.setRoles(roles);
return result;
}

如果要用上哈希盐对比密码,应该在该自定义realm构造函数里增加setCredentialsMatcher。

1
2
3
4
5
public DbShiroRealm(IUserService userService) {
this.userService = userService;
//因为数据库中的密码做了散列,所以使用shiro的散列Matcher
this.setCredentialsMatcher(new HashedCredentialsMatcher(Sha256Hash.ALGORITHM_NAME));
}

评论