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;
|
}
|
}
|