XiaoRuby
2023-07-13 27e9d7d2c7db63c5f12c83e069980213398e8337
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.yuanchu.limslaboratory.shiro.realm;
 
import com.yuanchu.limslaboratory.pojo.User;
import com.yuanchu.limslaboratory.shiro.JwtToken;
import com.yuanchu.limslaboratory.utils.RedisUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
 
public class JwtRealm extends AuthorizingRealm {
    /**
     * 限定这个 Realm 只处理我们自定义的 JwtToken
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }
 
    /**
     * 此处的 SimpleAuthenticationInfo 可返回任意值,密码校验时不会用到它
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authcToken;
        if (jwtToken.getPrincipal() == null) {
            throw new AccountException("Token参数异常!");
        }
        // 当前用户
        String account = jwtToken.getPrincipal().toString();
        // 当前用户的token
        String credentials = (String)jwtToken.getCredentials();
        User user = (User) RedisUtil.get(credentials);
        // 用户不存在
        if (user == null) {
            throw new UnknownAccountException("用户不存在!");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, account, getName());
        return info;
    }
 
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }
}