zhoux 2 лет назад
Родитель
Сommit
c106f618eb

+ 29 - 0
src/main/java/com/dk/gateway/enums/ErrorCodeEnum.java

@@ -0,0 +1,29 @@
+package com.dk.gateway.enums;
+
+/**
+ * @author H_x_d
+ * 错误信息
+ * @date_time 2021-12-22 17:15
+ */
+public enum ErrorCodeEnum {
+    USER_TOKEN_EXPIRE(1002, "当前用户在其他设备上登录,此客户端已退出登录。"),
+
+    ;
+
+    private int code;
+    private String message;
+
+    ErrorCodeEnum(int code, String message) {
+        this.code = code;
+        this.message = message;
+    }
+
+    public int getCode() {
+        return code;
+    }
+
+    public String getMessage() {
+        return message;
+    }
+}
+

+ 49 - 10
src/main/java/com/dk/gateway/oauth/filter/Oauth2Filter.java

@@ -2,17 +2,20 @@ package com.dk.gateway.oauth.filter;
 
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
+import com.dk.gateway.enums.ErrorCodeEnum;
 import com.dk.gateway.oauth.util.AESSecurityUtil;
 import com.dk.gateway.oauth.util.JwtUtil;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.cloud.gateway.filter.GatewayFilterChain;
 import org.springframework.cloud.gateway.filter.GlobalFilter;
 import org.springframework.core.Ordered;
 import org.springframework.core.io.buffer.DataBuffer;
+import org.springframework.data.redis.core.StringRedisTemplate;
 import org.springframework.http.HttpStatus;
 import org.springframework.http.MediaType;
 import org.springframework.http.server.reactive.ServerHttpResponse;
@@ -20,8 +23,10 @@ import org.springframework.stereotype.Component;
 import org.springframework.web.server.ServerWebExchange;
 import reactor.core.publisher.Mono;
 
+import javax.annotation.Resource;
 import java.nio.charset.StandardCharsets;
 import java.util.Arrays;
+import java.util.Map;
 
 @Slf4j
 @Component
@@ -34,6 +39,10 @@ public class Oauth2Filter implements GlobalFilter, Ordered {
     @Value("${aes-key}")
     private String AESKey;
 
+    @Resource
+    private StringRedisTemplate stringRedisTemplate;
+
+
     @Override
     public int getOrder() {
         return 0;
@@ -44,34 +53,64 @@ public class Oauth2Filter implements GlobalFilter, Ordered {
         ServerHttpResponse response = exchange.getResponse();
         // 过滤掉不需要进行权限控制的服务
         String path = exchange.getRequest().getPath().toString();
-        logger.info("-------请求地址----{}" , path);
+        logger.info("-------请求地址----{}", path);
         String[] filterPaths = filterPath.split(";");
         if (Arrays.asList(filterPaths).contains(path)) {
-            logger.info("------不需要权限----{}" , path);
+            logger.info("------不需要权限----{}", path);
             return chain.filter(exchange);
         }
-        if(path.contains("/wxapi")){
-            logger.info("------小程序接口----{}" , path);
+        if (path.contains("/wxapi")) {
+            logger.info("------小程序接口----{}", path);
             return chain.filter(exchange);
         }
-        if(path.contains("/druid")){
-            logger.info("------druid接口----{}" , path);
+        if (path.contains("/druid")) {
+            logger.info("------druid接口----{}", path);
             return chain.filter(exchange);
         }
-        if(path.contains("/scheduler-server")){
-            logger.info("------定时任务接口----{}" , path);
+        if (path.contains("/scheduler-server")) {
+            logger.info("------定时任务接口----{}", path);
             return chain.filter(exchange);
         }
-        if(path.contains("/export")){
+        if (path.contains("/export")) {
             logger.info("------export接口----{}" + path);
             return chain.filter(exchange);
         }
         // 获取token
         String accessToken = exchange.getRequest().getHeaders().getFirst("Authorization");
         String decodedAccessToken = accessToken;
+        logger.info("------获取的token----{}", decodedAccessToken);
+
+        if (accessToken != null) {
+            String[] tokens = accessToken.split(" ");
+            try {
+                String decrypt = AESSecurityUtil.decrypt(AESKey, tokens[1]);
+                String userId = JwtUtil.getUserId(decrypt);
+                String appCode = JwtUtil.getAppCode(decrypt);
+                String mapJson = stringRedisTemplate.opsForValue().get("REDIS_USER_LOGIN_" + userId + "_" + appCode);
+                Map<String, Object> userMap = JSON.parseObject(mapJson);
+                String token = "Bearer " + userMap.get("accessToken");
+                if (accessToken.equals(token) ) {
+                    //定义响应体
+                    JSONObject result = new JSONObject() {{
+                        put("code", ErrorCodeEnum.USER_TOKEN_EXPIRE.getCode());
+                        put("message", ErrorCodeEnum.USER_TOKEN_EXPIRE.getMessage());
+                        put("data", "");
+                    }};
+                    //作JSON转换
+                    byte[] bytes = JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8);
+                    //调用bufferFactory方法,生成DataBuffer对象
+                    DataBuffer buffer = response.bufferFactory().wrap(bytes);
+                    //调用Mono中的just方法,返回要写给前端的JSON数据
+                    return response.writeWith(Mono.just(buffer));
+                }
+            } catch (Exception e) {
+                return chain.filter(exchange);
+            }
+        }
+
         String jwt = null;
         String userName = null;
-        logger.info("------获取的token----{}" , decodedAccessToken);
+
 //        if (StringUtils.isNotBlank(decodedAccessToken)) {
 //            String[] tokens = decodedAccessToken.split(" ");
 //            // 验证Access Token

+ 25 - 3
src/main/java/com/dk/gateway/oauth/util/JwtUtil.java

@@ -9,9 +9,11 @@ import lombok.extern.slf4j.Slf4j;
 
 @Slf4j
 public class JwtUtil {
+    public static final String SHIRO_CP_ID = "cpId";
+    public static final String SHIRO_CP_CODE = "cpCode";
     public static final String SHIRO_USER_NAME = "username";
     public static final String SHIRO_USER_ID = "userId";
-    public static final String SHIRO_COMPANY_ID = "companyId";
+    public static final String SHIRO_APP_CODE = "appCode";
     public static final String SHIRO_CLIENT_ID = "clientId";
     public static final String SHIRO_USER_SALT = "salt";
     public static final String SHIRO_ISSUER = "Issuer";
@@ -73,10 +75,30 @@ public class JwtUtil {
         }
     }
 
-    public static String getCompanyId(String token) {
+    public static String getCpId(String token) {
         try {
             DecodedJWT jwt = JWT.decode(token);
-            return jwt.getClaim(SHIRO_COMPANY_ID).asString();
+            return jwt.getClaim(SHIRO_CP_ID).asString();
+        } catch (JWTDecodeException e) {
+            log.error("error:{}", e.getMessage());
+            return null;
+        }
+    }
+
+    public static String getAppCode(String token) {
+        try {
+            DecodedJWT jwt = JWT.decode(token);
+            return jwt.getClaim(SHIRO_APP_CODE).asString();
+        } catch (JWTDecodeException e) {
+            log.error("error:{}", e.getMessage());
+            return null;
+        }
+    }
+
+    public static String getCpCode(String token) {
+        try {
+            DecodedJWT jwt = JWT.decode(token);
+            return jwt.getClaim(SHIRO_CP_CODE).asString();
         } catch (JWTDecodeException e) {
             log.error("error:{}", e.getMessage());
             return null;