kongdeqiang
2026-10-12 7c687dd3c8fba9f7632f5e29d94a708e5f497abd
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
package com.custom.webui.security;
 
import com.custom.webui.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
 
import java.io.IOException;
 
/**
 * JWT 认证过滤器。
 *
 * <p>token 来源支持两种,按优先级:
 * <ol>
 *   <li>{@code Authorization: Bearer {token}} —— 普通 XHR 请求使用,是标准姿势</li>
 *   <li>{@code ?token={token}} —— 仅供 SSE 接口使用</li>
 * </ol>
 *
 * <p><b>为什么 SSE 必须支持 query 参数?</b>
 * 浏览器原生 {@code EventSource} 无法自定义请求头,拿不到 Authorization。
 * 备选方案是用 fetch + ReadableStream 手动解析 SSE,但那会偏离
 * 文档约定的「EventSource 原生长连接」实现。
 * 折中做法是允许 query 传 token,并在生产环境通过以下手段收敛风险:
 * nginx 侧对 /api/chats/{chatId}/stream 关闭 access_log 的 query 记录、
 * 强制 HTTPS 防止明文泄露。这一点在 README 的「已知取舍」中有说明。
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
 
    private static final String BEARER_PREFIX = "Bearer ";
 
    private final JwtUtil jwtUtil;
 
    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request,
                                    @NonNull HttpServletResponse response,
                                    @NonNull FilterChain filterChain)
            throws ServletException, IOException {
 
        // 已有认证信息则不重复处理(例如测试环境预设的上下文)
        if (SecurityContextHolder.getContext().getAuthentication() == null) {
            String token = resolveToken(request);
            if (token != null) {
                Claims claims = jwtUtil.parse(token);
                if (claims != null) {
                    try {
                        Long userId = Long.valueOf(claims.getSubject());
                        String username = claims.get("username", String.class);
                        String role = claims.get("role", String.class);
                        AuthPrincipal principal = new AuthPrincipal(
                                userId,
                                username == null ? "unknown" : username,
                                role == null ? "user" : role);
 
                        UsernamePasswordAuthenticationToken authentication =
                                new UsernamePasswordAuthenticationToken(
                                        principal, null, principal.getAuthorities());
                        authentication.setDetails(
                                new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    } catch (NumberFormatException e) {
                        log.debug("JWT subject 不是合法用户 id");
                    }
                }
            }
        }
 
        filterChain.doFilter(request, response);
    }
 
    /** 依次从 Authorization 头、token query 参数中提取 token */
    private String resolveToken(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        if (header != null && header.startsWith(BEARER_PREFIX)) {
            String token = header.substring(BEARER_PREFIX.length()).trim();
            if (!token.isEmpty()) {
                return token;
            }
        }
        String param = request.getParameter("token");
        if (param != null && !param.isBlank()) {
            return param.trim();
        }
        return null;
    }
}