Просмотр исходного кода

优化解决拦截器接口黑白名单未生效问题

zhaojinyu 4 дней назад
Родитель
Сommit
71728c9525

+ 58 - 9
base-modules/service-license/service-license-client/src/main/java/com/usky/license/client/LicenseCheckInterceptor.java

@@ -3,11 +3,19 @@ package com.usky.license.client;
 import com.usky.common.core.exception.BusinessException;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.server.PathContainer;
 import org.springframework.stereotype.Component;
 import org.springframework.web.servlet.HandlerInterceptor;
+import org.springframework.web.util.pattern.PathPattern;
+import org.springframework.web.util.pattern.PathPatternParser;
 
+import javax.annotation.PostConstruct;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
 
 @Component
 @Slf4j
@@ -16,19 +24,60 @@ public class LicenseCheckInterceptor implements HandlerInterceptor {
     @Autowired
     private LicenseVerify licenseVerify;
 
+    @Value("${license.addpaths}")
+    private String addpaths;
+
+    @Value("${license.excludepaths}")
+    private String excludepaths;
+
+    private List<PathPattern> licensePaths;
+    private List<PathPattern> excludePaths;
+
+    @PostConstruct
+    public void init() {
+        // 解析 addpaths 为 PathPattern 列表
+        PathPatternParser parser = new PathPatternParser();
+        licensePaths = Arrays.stream(addpaths.split(","))
+                .map(String::trim) // 去掉多余的空格
+                .map(path -> parser.parse(path))
+                .collect(Collectors.toList());
+
+        // 解析 excludepaths 为 PathPattern 列表
+        excludePaths = Arrays.stream(excludepaths.split(","))
+                .map(String::trim) // 去掉多余的空格
+                .map(path -> parser.parse(path))
+                .collect(Collectors.toList());
+    }
+
     @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
-        // 临时添加:打印 licenseVerify 是否为 null
-        if (licenseVerify == null) {
-            log.error("LicenseVerify 注入失败,为 null!");
-            throw new BusinessException("License 验证组件加载失败");
+        // 获取当前请求的 URI
+        String requestURI = request.getRequestURI();
+        log.info("当前请求 URI: {}", requestURI);
+
+        // 检查是否在排除路径中
+        PathContainer pathContainer = PathContainer.parsePath(requestURI);
+        for (PathPattern excludePath : excludePaths) {
+            if (excludePath.matches(pathContainer)) {
+                return true; // 不拦截
+            }
         }
 
-        boolean verifyResult = licenseVerify.verify();
-        if (!verifyResult) {
-            log.warn("License 无效,拒绝服务");
-            throw new BusinessException("License 无效,请检查证书是否授权或已过期");
+        // 检查是否在拦截路径中
+        boolean isMatched = licensePaths.stream()
+                .anyMatch(pathPattern -> pathPattern.matches(pathContainer));
+
+        if (isMatched) {
+            log.info("请求 URI 匹配拦截路径,开始验证 License");
+            boolean verifyResult = licenseVerify.verify();
+            if (!verifyResult) {
+                log.warn("License 无效,拒绝服务");
+                throw new BusinessException("License 无效,请检查证书是否授权或已过期");
+            }
+        } else {
+            log.info("请求 URI 不在拦截路径中,直接放行");
         }
+
         return true;
     }
-}
+}

+ 34 - 4
base-modules/service-system/service-system-biz/src/main/java/com/usky/system/service/config/WebConfig.java

@@ -2,21 +2,51 @@ package com.usky.system.service.config;
 
 import com.usky.license.client.LicenseCheckInterceptor;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
 @Configuration
 public class WebConfig implements WebMvcConfigurer {
 
     @Autowired
     private LicenseCheckInterceptor licenseCheckInterceptor;
 
+    @Value("${license.addpaths}")
+    private String addpaths;
+
+    @Value("${license.excludepaths}")
+    private String excludepaths;
+
     @Override
     public void addInterceptors(InterceptorRegistry registry) {
-        // 排除掉 swagger、actuator 等
+        // 将 addpaths 和 excludepaths 字符串解析为列表
+        List<String> addpathList = Arrays.stream(addpaths.split(","))
+                .map(String::trim) // 去掉多余的空格
+                .collect(Collectors.toList());
+        List<String> excludePathList = Arrays.stream(excludepaths.split(","))
+                .map(String::trim) // 去掉多余的空格
+                .collect(Collectors.toList());
+
+        // 确保路径格式正确
+        addpathList = addpathList.stream()
+                .map(path -> path.replaceAll("\\*\\*", "/**")) // 将 ** 替换为 /**
+                .map(path -> path.replaceAll("\\*", "/.*")) // 将 * 替换为 /.*
+                .collect(Collectors.toList());
+
+        excludePathList = excludePathList.stream()
+                .map(path -> path.replaceAll("\\*\\*", "/**")) // 将 ** 替换为 /**
+                .map(path -> path.replaceAll("\\*", "/.*")) // 将 * 替换为 /.*
+                .collect(Collectors.toList());
+
+        // 注册拦截器
         registry.addInterceptor(licenseCheckInterceptor)
-                .excludePathPatterns("/error", "/swagger-ui/**", "/v3/api-docs/**",
-                        "/actuator/**", "/license/**");
+                .addPathPatterns(addpathList.toArray(new String[0]))
+                .excludePathPatterns(excludePathList.toArray(new String[0]));
     }
-}
+}