#
luxiaotao1123
2024-01-29 2db8378d205cf4dbf273d8aa63a401a88e562395
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
package com.zy.asrs.wcs.common.security;
 
import com.zy.asrs.framework.common.Cools;
import com.zy.asrs.wcs.common.config.ConfigProperties;
import com.zy.asrs.wcs.common.constant.Constants;
import com.zy.asrs.wcs.sys.entity.Menu;
import com.zy.asrs.wcs.sys.entity.User;
import com.zy.asrs.wcs.sys.service.UserLoginService;
import com.zy.asrs.wcs.sys.service.UserService;
import com.zy.asrs.wcs.utils.HttpUtils;
import com.zy.asrs.wcs.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
 
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
 
/**
 * 处理携带token的请求过滤器
 *
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
 
    public static final ArrayList<String> WHITE_KEY = new ArrayList<String>(){
        private static final long serialVersionUID = 1L;
        {
            add("xltys1995");
        }
    };
 
    @Resource
    private ConfigProperties configProperties;
    @Resource
    private UserService userService;
    @Resource
    private UserLoginService userLoginService;
 
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String access_token = JwtUtil.getAccessToken(request);
        for (String filterPath : SecurityConfig.FILTER_PATH) {
            AntPathRequestMatcher antPathMatcher = new AntPathRequestMatcher(filterPath);
            if (antPathMatcher.matches(request)) {
                access_token = "";
            }
        }
        if (!Cools.isEmpty(access_token)) {
            try {
                User user;
                if (WHITE_KEY.contains(access_token)) {
                    user = userService.getByUsername("openapi", 2);
                    if (user == null) {
                        throw new UsernameNotFoundException("Username not found");
                    }
                    List<Menu> authorities = user.getAuthorities().stream()
                            .filter(m -> !Cools.isEmpty(m.getAuthority())).collect(Collectors.toList());
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            user, null, authorities);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                } else {
                    // 解析token
                    Claims claims = JwtUtil.parseToken(access_token, configProperties.getTokenKey());
                    JwtSubject jwtSubject = JwtUtil.getJwtSubject(claims);
                    user = userService.getByUsername(jwtSubject.getUsername(), jwtSubject.getTenantId());
                    if (user == null) {
                        throw new UsernameNotFoundException("Username not found");
                    }
                    List<Menu> authorities = user.getAuthorities().stream()
                            .filter(m -> !Cools.isEmpty(m.getAuthority())).collect(Collectors.toList());
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            user, null, authorities);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    // token将要过期签发新token, 防止突然退出登录
                    long expiration = (claims.getExpiration().getTime() - new Date().getTime()) / 1000 / 60;
                    if (expiration < configProperties.getTokenRefreshTime()) {
                        String token = JwtUtil.buildToken(jwtSubject, configProperties.getTokenExpireTime(),
                                configProperties.getTokenKey());
                        response.addHeader(Constants.TOKEN_HEADER_NAME, token);
                        userLoginService.saveAsync(user.getUsername(), LoginRecord.TYPE_REFRESH, null,
                                user.getTenantId(), request);
                    }
                }
            } catch (ExpiredJwtException e) {
                HttpUtils.responseError(response, Constants.TOKEN_EXPIRED_CODE, Constants.TOKEN_EXPIRED_MSG,
                        e.getMessage());
                return;
            } catch (Exception e) {
                HttpUtils.responseError(response, Constants.BAD_CREDENTIALS_CODE, Constants.BAD_CREDENTIALS_MSG,
                        e.toString());
                return;
            }
        }
        chain.doFilter(request, response);
    }
 
}