zyx 2 years ago
parent
commit
6829c3fcbe

+ 11 - 1
src/main/java/com/sxtvs/open/core/auth/HttpContextUtil.java

@@ -21,11 +21,21 @@ public class HttpContextUtil {
     }
 
     public static void setRequestId() {
-
         Optional.ofNullable(RequestContextHolder.getRequestAttributes())
                 .ifPresent(x -> {
                     var requestId = IdUtil.nanoId();
                     x.setAttribute("requestId", requestId, RequestAttributes.SCOPE_REQUEST);
                 });
     }
+
+    public static Optional<String> getToken() {
+        return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
+                .map(x -> x.getAttribute("token", RequestAttributes.SCOPE_REQUEST))
+                .map(Object::toString);
+    }
+
+    public static void setToken(String token) {
+        Optional.ofNullable(RequestContextHolder.getRequestAttributes())
+                .ifPresent(x -> x.setAttribute("token", token, RequestAttributes.SCOPE_REQUEST));
+    }
 }

+ 3 - 4
src/main/java/com/sxtvs/open/core/auth/LoginInterceptor.java

@@ -1,7 +1,6 @@
 package com.sxtvs.open.core.auth;
 
 
-import cn.hutool.core.util.IdUtil;
 import com.sxtvs.open.core.advice.BizException;
 import com.sxtvs.open.core.conf.Constant;
 import jakarta.servlet.http.HttpServletRequest;
@@ -13,12 +12,11 @@ import java.lang.reflect.Method;
 
 public class LoginInterceptor implements AsyncHandlerInterceptor {
     @Override
-    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
-        if (!(handler instanceof HandlerMethod)) {
+    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
+        if (!(handler instanceof HandlerMethod handlerMethod)) {
             return true;
         }
         HttpContextUtil.setRequestId();
-        HandlerMethod handlerMethod = (HandlerMethod) handler;
         Method method = handlerMethod.getMethod();
 
         LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
@@ -32,6 +30,7 @@ public class LoginInterceptor implements AsyncHandlerInterceptor {
         if (!AESUtil.isOk(token)) {
             throw new BizException("没有登录");
         }
+        HttpContextUtil.setToken(token);
 
         return true;
     }