郑永安
2023-06-19 7a6abd05683528032687c75e80e0bd2030a3e46c
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package com.gkhy.safePlatform.config.security;
 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gkhy.safePlatform.account.rpc.apimodel.AccountAuthService;
import com.gkhy.safePlatform.commons.co.ContextCacheAuthority;
import com.gkhy.safePlatform.commons.co.ContextCacheUser;
import com.gkhy.safePlatform.commons.enums.RedisKeyEnum;
import com.gkhy.safePlatform.commons.enums.ResultCodes;
import com.gkhy.safePlatform.commons.exception.BusinessException;
import com.gkhy.safePlatform.commons.utils.RPCUtils;
import com.gkhy.safePlatform.commons.utils.RequestContextHolder;
import com.gkhy.safePlatform.commons.utils.StringUtils;
import com.gkhy.safePlatform.commons.vo.ResultVO;
import com.gkhy.safePlatform.config.redis.RedisUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
 
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
 
/**
* @Description: token登录过滤器
*/
@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter  {
 
    @Autowired
    private TokenConfig tokenConfig;
    @DubboReference(check = false)
    private AccountAuthService userAccountService;
    @Autowired
    private RedisUtils redisUtils;
 
 
 
    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException {
 
        try {
            //获取当前认证成功用户权限信息
            UsernamePasswordAuthenticationToken authRequest = getAuthentication(req, resp);
            if (authRequest != null) {
                SecurityContextHolder.getContext().setAuthentication(authRequest);
            }
            // 执行下一个 filter 过滤器链
            chain.doFilter(req, resp);
        } catch (BusinessException e) {
            // 返回异常
            this.writeJSON(req, resp, new ResultVO<>(e.getCode(),e.getMessage()));
        }
 
    }
 
 
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest req,HttpServletResponse resp) {
        // header获取token
        String authToken = req.getHeader(tokenConfig.getHeader());
        String loginUserId = req.getHeader(tokenConfig.getLoginUserHeader());
 
        if(authToken != null) {
            // header 传入 userId
            if (StringUtils.isBlank(loginUserId)) {
                throw new BusinessException(ResultCodes.CLIENT_CREDENTIALS_LACK);
            }
            // 登录成功时,会将权限数据存入redis
            // 这里是验证获取权限信息
            // 1.从redis中获取对应该用户的权限信息
            String accessTokenKey = RedisKeyEnum.authKey(RedisKeyEnum.AUTH_TOKEN, loginUserId);
            Object o = redisUtils.get(accessTokenKey);
            // 2.token是否存在
            if (o == null) {
                // 是否存在 uid未登录
                throw new BusinessException(ResultCodes.CLIENT_CREDENTIALS_TOKEN_INVALID);
            }else{
 
                Long userId = Long.valueOf(loginUserId);
                ContextCacheUser ContextCacheUser = JSONObject.parseObject(o.toString(), ContextCacheUser.class);
                assert userId.equals(ContextCacheUser.getUid());
                if ( !authToken.equals(ContextCacheUser.getAccessToken())) {
                    throw new BusinessException(ResultCodes.CLIENT_CREDENTIALS_TOKEN_INVALID);
                }
 
                Long expireSecondsLeft = redisUtils.getExpireTime(accessTokenKey);
                // 60m 内请求则续期 时长为原本的有效时间
                if (expireSecondsLeft != null && 0L < expireSecondsLeft && expireSecondsLeft < 60 * 60) {
                    redisUtils.resetKeyExpireTime(accessTokenKey, tokenConfig.getExpiration());
                }
                // 3.redis获取权限
                String authoritiesKey = RedisKeyEnum.authKey(RedisKeyEnum.AUTH_AUTHORITIES, userId);
                Object oo = redisUtils.get(authoritiesKey);
                List<GrantedAuthority> authorities = new ArrayList<>();
                // 4.redis中是否存在
                if (oo != null) {
                    List<ContextCacheAuthority> cacheAuthorities = JSONArray.parseArray(oo.toString(), ContextCacheAuthority.class);
                    for (ContextCacheAuthority cacheAuthority: cacheAuthorities) {
                        authorities.add(new SimpleGrantedAuthority(cacheAuthority.getAuthority()));
                    }
                }else {
                    // 6.不存在=>数据库查询
                    ResultVO<String> rpcResultRole = userAccountService.getUserRoleCodeByUserId(userId);
 
                    if (rpcResultRole == null) {
                        throw new BusinessException(ResultCodes.RPC_RESULT_NULL);
                    }
                    if (!ResultCodes.OK.getCode().equals(rpcResultRole.getCode())) {
                        throw new BusinessException(rpcResultRole.getCode(), rpcResultRole.getMsg());
                    }
                    if (rpcResultRole.getData() == null) {
                        throw new BusinessException(ResultCodes.RPC_DATA_NULL);
                    }
                    if (!(rpcResultRole.getData() instanceof String)) {
                        throw new BusinessException(ResultCodes.RPC_DATA_TYPE_NOT_MATCH);
                    }
 
                    // role
                    authorities.add(new SimpleGrantedAuthority("ROLE_" + rpcResultRole.getData().toString()));
 
                    // permission
                    ResultVO<List<String>> rpcResultPermission = userAccountService.getUserPermissionByUserId(userId);
 
                    if (rpcResultPermission == null) {
                        throw new BusinessException(ResultCodes.RPC_RESULT_NULL);
                    }
                    if (!ResultCodes.OK.getCode().equals(rpcResultPermission.getCode())) {
                        throw new BusinessException(rpcResultRole.getCode(), rpcResultRole.getMsg());
                    }
                    if (rpcResultPermission.getData() == null) {
                        throw new BusinessException(ResultCodes.RPC_DATA_NULL);
                    }
                    if (!(rpcResultPermission.getData() instanceof List)) {
                        throw new BusinessException(ResultCodes.RPC_DATA_TYPE_NOT_MATCH);
                    }
                    List<String> permissions = RPCUtils.castList(rpcResultPermission.getData(), String.class);
                    for (String permission : permissions) {
                        authorities.add(new SimpleGrantedAuthority(permission));
                    }
                }
                // threadLocal存入用户信息
                RequestContextHolder.contextUserLocal.set(ContextCacheUser);
                // security对象中存入登陆者信息
                return new UsernamePasswordAuthenticationToken(ContextCacheUser,authToken,authorities);
 
            }
 
 
 
 
 
 
        }
        return null;
    }
 
 
 
    protected void writeJSON(HttpServletRequest req,
                             HttpServletResponse resp,
                             ResultVO resultVO) throws IOException {
        // 设置编码格式
        resp.setContentType("text/json;charset=utf-8");
        // 处理跨域问题
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET");
 
        //输出JSON
        PrintWriter out = resp.getWriter();
        out.write(JSONObject.toJSONString(resultVO));
        out.flush();
        out.close();
    }
}