Selaa lähdekoodia

使用ThreadLocal记录用户信息

chenw 6 vuotta sitten
vanhempi
commit
92157a0464

+ 50 - 0
bi-core/src/main/java/com/usoftchina/bi/core/base/BaseContextHolder.java

@@ -0,0 +1,50 @@
+package com.usoftchina.bi.core.base;
+
+import org.springframework.util.ObjectUtils;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @Author chenwei
+ * @Date 2019-05-07
+ */
+public class BaseContextHolder {
+
+    private final static ThreadLocal<Map<String, Object>> contextHolder = new ThreadLocal<Map<String, Object>>();
+
+    public static void set(String key, Object value) {
+        Map<String, Object> map = contextHolder.get();
+        if (null == map) {
+            map = new HashMap<String, Object>(1);
+            contextHolder.set(map);
+        }
+        map.put(key, value);
+    }
+
+    public static Object get(String key) {
+        Map<String, Object> map = contextHolder.get();
+        if (null == map) {
+            return null;
+        }
+        return map.get(key);
+    }
+
+    public static int getUserId() {
+        Object value = get("userId");
+        return Integer.valueOf(String.valueOf(value));
+    }
+
+    public static void setUserId(int userId) {
+        set("userId", userId);
+    }
+
+    public static String getUserName() {
+        Object value = get("userName");
+        return String.valueOf(value);
+    }
+
+    public static void setUserName(String userName) {
+        set("userName", userName);
+    }
+}

+ 3 - 0
bi-server/src/main/java/com/usoftchina/bi/server/aspect/JwtTokenAspect.java

@@ -5,6 +5,7 @@ import com.auth0.jwt.JWTVerifier;
 import com.auth0.jwt.algorithms.Algorithm;
 import com.auth0.jwt.interfaces.Claim;
 import com.auth0.jwt.interfaces.DecodedJWT;
+import com.usoftchina.bi.core.base.BaseContextHolder;
 import com.usoftchina.bi.core.exception.MyException;
 import com.usoftchina.bi.server.model.po.TokenData;
 import com.usoftchina.bi.server.model.po.User;
@@ -91,6 +92,8 @@ public class JwtTokenAspect {
         } catch (MyException e) {
             throw new MyException(-505, "token过期");
         }
+        BaseContextHolder.setUserId(Integer.valueOf(jwt.getClaim("id").asString()));
+        BaseContextHolder.setUserName(jwt.getClaim("name").asString());
         return jwt.getClaims();
     }
 }