ccj 11 місяців тому
батько
коміт
f3e25feeaf

+ 44 - 23
src/main/java/com/zhaoliangsz/grainsearch/basic/config/WebConfig.java

@@ -24,29 +24,50 @@ import java.util.List;
  */
 
 @Configuration
-public class WebConfig implements WebMvcConfigurer {
-
-    //注入
-    @Resource
-    private LoginInterceptor loginInterceptor;
-
-    //拦截器
-    @Override
-    public void addInterceptors(InterceptorRegistry registry) {
-        registry.addInterceptor(loginInterceptor)
-                .addPathPatterns("/**") //拦截所有的 url
-                .excludePathPatterns("/v1/**/*")//排除url: /v1
-                .excludePathPatterns("/image/**")//排除 image(图像) 文件夹下的所有文件
-                .excludePathPatterns("/**/*.js")//排除任意深度目录下的所有".js"文件
-                .excludePathPatterns("/**/*.css");
-    }
+public class WebConfig {
+
+    @Value("${allowed-origins:*}")
+    private String allowedOrigins;
+
+    @Value("${allowed-headers:Access-Control-Allow-Headers,Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Authorization,Access-Control-Request-Headers}")
+    private String allowedHeaders;
+
     /**
-     * 移除 StringHttpMessageConverter
-     *
-     * @param converters
+     * 测试用,跨域访问
      */
-    @Override
-    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
-        converters.removeIf(converter -> converter instanceof StringHttpMessageConverter);
+    @Bean
+    public Filter corsFilter() {
+        return new Filter() {
+
+            @Override
+            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+                    throws IOException, ServletException {
+                HttpServletRequest req = ((HttpServletRequest) request);
+                HttpServletResponse res = (HttpServletResponse) response;
+                if ("*".equals(allowedOrigins) || allowedOrigins.contains(req.getHeader("Origin"))) {
+                    res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
+//					res.setHeader("Access-Control-Allow-Origin", allowedOrigins);
+                }
+
+                res.setHeader("Access-Control-Allow-Credentials", "true");
+                res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
+                res.setHeader("Access-Control-Allow-Headers", allowedHeaders);
+                if ("OPTIONS".equals(req.getMethod())) {
+                    response.getWriter().println("ok");
+                    return;
+                }
+                chain.doFilter(request, response);
+            }
+
+            @Override
+            public void init(FilterConfig filterConfig) throws ServletException {
+                // ignore
+            }
+
+            @Override
+            public void destroy() {
+                // ignore
+            }
+        };
     }
-}
+}