优化
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package com.emotion.interceptor;
|
||||
|
||||
import com.emotion.util.JwtUtil;
|
||||
import com.emotion.util.UserContextHolder;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -64,19 +65,32 @@ public class JwtAuthInterceptor implements HandlerInterceptor {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 从token中获取用户信息并设置到请求属性中
|
||||
// 从token中获取用户信息并设置到请求属性和上下文中
|
||||
String userId = jwtUtil.getUserIdFromToken(token);
|
||||
String username = jwtUtil.getUsernameFromToken(token);
|
||||
|
||||
|
||||
// 设置到请求属性中(兼容现有代码)
|
||||
request.setAttribute("userId", userId);
|
||||
request.setAttribute("username", username);
|
||||
request.setAttribute("token", token);
|
||||
|
||||
|
||||
// 设置到线程本地上下文中(推荐使用)
|
||||
UserContextHolder.setCurrentUserId(userId);
|
||||
UserContextHolder.setCurrentUsername(username);
|
||||
UserContextHolder.setCurrentToken(token);
|
||||
|
||||
log.debug("Token验证成功,用户: {} ({})", username, userId);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
|
||||
// 请求完成后清除用户上下文,防止内存泄漏
|
||||
UserContextHolder.clear();
|
||||
log.debug("请求完成,已清除用户上下文");
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为公开接口(不需要认证)
|
||||
*/
|
||||
@@ -88,11 +102,8 @@ public class JwtAuthInterceptor implements HandlerInterceptor {
|
||||
"/api/auth/captcha",
|
||||
"/api/auth/refresh-token",
|
||||
"/api/health",
|
||||
"/api/ws/chat",
|
||||
"/api/emotion-records", // 情绪记录接口
|
||||
"/api/emotion-summary", // 情绪总结接口
|
||||
"/message", // 消息接口
|
||||
"/swagger-ui",
|
||||
"/api/ws/chat",
|
||||
"/swagger-ui",
|
||||
"/v3/api-docs",
|
||||
"/actuator"
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user