|
|
@@ -5,6 +5,7 @@ import com.xuekairui.common.ErrorCode;
|
|
|
import com.xuekairui.common.Result;
|
|
|
import com.xuekairui.user.entity.User;
|
|
|
import com.xuekairui.user.mapper.UserMapper;
|
|
|
+
|
|
|
import com.xuekairui.user.util.JwtUtil;
|
|
|
import jakarta.servlet.FilterChain;
|
|
|
import jakarta.servlet.ServletException;
|
|
|
@@ -12,6 +13,7 @@ import jakarta.servlet.http.HttpServletRequest;
|
|
|
import jakarta.servlet.http.HttpServletResponse;
|
|
|
import lombok.RequiredArgsConstructor;
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.slf4j.MDC;
|
|
|
import org.springframework.http.HttpStatus;
|
|
|
import org.springframework.http.MediaType;
|
|
|
import org.springframework.lang.NonNull;
|
|
|
@@ -21,10 +23,11 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
|
|
import org.springframework.security.core.context.SecurityContextHolder;
|
|
|
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
|
|
import org.springframework.stereotype.Component;
|
|
|
-import org.slf4j.MDC;
|
|
|
import org.springframework.util.StringUtils;
|
|
|
import org.springframework.web.filter.OncePerRequestFilter;
|
|
|
|
|
|
+import io.jsonwebtoken.Claims;
|
|
|
+
|
|
|
import java.io.IOException;
|
|
|
import java.nio.charset.StandardCharsets;
|
|
|
import java.util.Collections;
|
|
|
@@ -70,69 +73,78 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
|
|
String token = extractToken(request);
|
|
|
String path = request.getRequestURI();
|
|
|
boolean isHeartbeat = "/api/auth/heartbeat".equals(path);
|
|
|
- if (token != null && SecurityContextHolder.getContext().getAuthentication() == null) {
|
|
|
- try {
|
|
|
- boolean isLenientPath = isLenientPath(request);
|
|
|
- String tokenType = isLenientPath
|
|
|
- ? jwtUtil.parseTokenLenient(token).get("type", String.class)
|
|
|
- : jwtUtil.getTokenType(token);
|
|
|
- if ("access".equals(tokenType)) {
|
|
|
- Long userId = isLenientPath
|
|
|
- ? jwtUtil.parseTokenLenient(token).get("userId", Long.class)
|
|
|
- : jwtUtil.getUserId(token);
|
|
|
- Long tokenVer = isLenientPath
|
|
|
- ? getTokenVersionLenient(token)
|
|
|
- : jwtUtil.getTokenVersion(token);
|
|
|
- // 单设备登录校验:验证 token 中的版本号与当前最新版本一致
|
|
|
- if (!isTokenVersionValid(userId, tokenVer)) {
|
|
|
- log.info("用户 {} 的Token版本号不匹配(已在其他设备登录),拒绝访问", userId);
|
|
|
- writeKickedResponse(response);
|
|
|
- return;
|
|
|
- }
|
|
|
|
|
|
- String role = isLenientPath
|
|
|
- ? jwtUtil.parseTokenLenient(token).get("role", String.class)
|
|
|
- : jwtUtil.getRole(token);
|
|
|
- if (role == null) {
|
|
|
- role = "USER";
|
|
|
+ // 尽早从 token 中提取 userId 注入 MDC(宽容模式,过期 token 也能提取)
|
|
|
+ extractUidForMdc(token);
|
|
|
+
|
|
|
+ try {
|
|
|
+ if (token != null && !token.isEmpty() && SecurityContextHolder.getContext().getAuthentication() == null) {
|
|
|
+ try {
|
|
|
+ boolean isLenientPath = isLenientPath(request);
|
|
|
+ Claims claims;
|
|
|
+ if (isLenientPath) {
|
|
|
+ // 宽容模式:一次解析 JWT,避免重复调用 parseTokenLenient
|
|
|
+ claims = jwtUtil.parseTokenLenient(token);
|
|
|
+ } else {
|
|
|
+ // 严格模式:一次解析 JWT,避免重复调用 parseToken
|
|
|
+ claims = jwtUtil.parseToken(token);
|
|
|
+ }
|
|
|
+ String tokenType = claims.get("type", String.class);
|
|
|
+ Long userId = claims.get("userId", Long.class);
|
|
|
+ Long tokenVer = getTokenVersionFromClaims(claims);
|
|
|
+ String role = claims.get("role", String.class);
|
|
|
+
|
|
|
+ // 确保 MDC 中有 uid(extractUidForMdc 可能已设置,此处兜底)
|
|
|
+ if (userId != null) {
|
|
|
+ MDC.put("uid", String.valueOf(userId));
|
|
|
}
|
|
|
|
|
|
- List<GrantedAuthority> authorities = Collections.singletonList(
|
|
|
- new SimpleGrantedAuthority("ROLE_" + role)
|
|
|
- );
|
|
|
-
|
|
|
- UsernamePasswordAuthenticationToken authentication =
|
|
|
- new UsernamePasswordAuthenticationToken(
|
|
|
- userId,
|
|
|
- null,
|
|
|
- authorities
|
|
|
- );
|
|
|
- authentication.setDetails(
|
|
|
- new WebAuthenticationDetailsSource().buildDetails(request)
|
|
|
- );
|
|
|
-
|
|
|
- SecurityContextHolder.getContext().setAuthentication(authentication);
|
|
|
-
|
|
|
- // 设置请求属性,供控制器直接使用
|
|
|
- request.setAttribute("userId", userId);
|
|
|
- request.setAttribute("role", role);
|
|
|
-
|
|
|
- // 尽早注入用户ID到MDC,使链路中后续日志都能带上uid
|
|
|
- MDC.put("uid", String.valueOf(userId));
|
|
|
- } else if (isHeartbeat) {
|
|
|
- log.warn("[heartbeat] 401原因: token类型不是access,实际type={},请用accessToken调用heartbeat", tokenType);
|
|
|
+ if ("access".equals(tokenType)) {
|
|
|
+ // 尽早设置 userId 到 request attribute,供后续 RequestLoggingFilter 日志使用
|
|
|
+ request.setAttribute("userId", userId);
|
|
|
+
|
|
|
+ // 单设备登录校验:验证 token 中的版本号与当前最新版本一致
|
|
|
+ if (!isTokenVersionValid(userId, tokenVer)) {
|
|
|
+ log.info("用户 {} 的Token版本号不匹配(已在其他设备登录),拒绝访问", userId);
|
|
|
+ writeKickedResponse(response);
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ if (role == null) {
|
|
|
+ role = "USER";
|
|
|
+ }
|
|
|
+
|
|
|
+ List<GrantedAuthority> authorities = Collections.singletonList(
|
|
|
+ new SimpleGrantedAuthority("ROLE_" + role)
|
|
|
+ );
|
|
|
+
|
|
|
+ UsernamePasswordAuthenticationToken authentication =
|
|
|
+ new UsernamePasswordAuthenticationToken(
|
|
|
+ userId,
|
|
|
+ null,
|
|
|
+ authorities
|
|
|
+ );
|
|
|
+ authentication.setDetails(
|
|
|
+ new WebAuthenticationDetailsSource().buildDetails(request)
|
|
|
+ );
|
|
|
+
|
|
|
+ SecurityContextHolder.getContext().setAuthentication(authentication);
|
|
|
+
|
|
|
+ // 设置请求属性,供控制器使用
|
|
|
+ request.setAttribute("role", role);
|
|
|
+ } else if (isHeartbeat) {
|
|
|
+ log.warn("[heartbeat] 401原因: token类型不是access,实际type={},请用accessToken调用heartbeat", tokenType);
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("JWT认证失败: {}", e.getMessage());
|
|
|
+ SecurityContextHolder.clearContext();
|
|
|
}
|
|
|
- } catch (Exception e) {
|
|
|
- log.warn("JWT认证失败: {}", e.getMessage());
|
|
|
- SecurityContextHolder.clearContext();
|
|
|
}
|
|
|
- }
|
|
|
|
|
|
- try {
|
|
|
filterChain.doFilter(request, response);
|
|
|
} finally {
|
|
|
- // 清理当前过滤器注入的uid,避免跨请求泄漏
|
|
|
+ // 清理 uid,RequestLoggingFilter 会从 request attribute 重新获取 uid 用于日志
|
|
|
MDC.remove("uid");
|
|
|
+ SecurityContextHolder.clearContext();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
@@ -189,10 +201,10 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
- /** 从可能已过期的 token 中提取版本号 */
|
|
|
- private Long getTokenVersionLenient(String token) {
|
|
|
+ /** 从已解析的 Claims 中提取版本号(避免重复解析 JWT) */
|
|
|
+ private Long getTokenVersionFromClaims(Claims claims) {
|
|
|
try {
|
|
|
- Object version = jwtUtil.parseTokenLenient(token).get("tokenVersion");
|
|
|
+ Object version = claims.get("tokenVersion");
|
|
|
if (version instanceof Number) {
|
|
|
return ((Number) version).longValue();
|
|
|
}
|
|
|
@@ -201,4 +213,19 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
|
|
return 0L;
|
|
|
}
|
|
|
}
|
|
|
+
|
|
|
+ /** 从 token 中提取 userId 注入 MDC,便于整个请求链路的日志带上 uid */
|
|
|
+ private void extractUidForMdc(String token) {
|
|
|
+ if (token == null || token.isEmpty()) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ Long uid = jwtUtil.parseTokenLenient(token).get("userId", Long.class);
|
|
|
+ if (uid != null) {
|
|
|
+ MDC.put("uid", String.valueOf(uid));
|
|
|
+ }
|
|
|
+ } catch (Exception ignored) {
|
|
|
+ // token 完全无法解析,忽略
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|