From 55c658b50f99e41cfce3c425c652d268d0d71857 Mon Sep 17 00:00:00 2001 From: fengshuonan Date: Tue, 13 Apr 2021 18:25:11 +0800 Subject: [PATCH] =?UTF-8?q?=E3=80=907.0.3=E3=80=91=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E8=B7=A8=E5=9F=9F=E6=8B=A6=E6=88=AA=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../web/OptionsSecurityInterceptor.java | 36 +++++++++++++++++++ .../config/web/SpringMvcConfiguration.java | 4 +++ 2 files changed, 40 insertions(+) create mode 100644 src/main/java/cn/stylefeng/guns/config/web/OptionsSecurityInterceptor.java diff --git a/src/main/java/cn/stylefeng/guns/config/web/OptionsSecurityInterceptor.java b/src/main/java/cn/stylefeng/guns/config/web/OptionsSecurityInterceptor.java new file mode 100644 index 00000000..3cc89165 --- /dev/null +++ b/src/main/java/cn/stylefeng/guns/config/web/OptionsSecurityInterceptor.java @@ -0,0 +1,36 @@ +package cn.stylefeng.guns.config.web; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * 跨域拦截器 + * + * @author fengshuonan + * @date 2021/4/13 18:24 + */ +@Component +@Slf4j +public class OptionsSecurityInterceptor implements HandlerInterceptor { + + /** + * 添加跨域允许的header + * + * @author fengshuonan + * @date 2021/4/13 18:24 + */ + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { + response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); + response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); + response.setHeader("Access-Control-Max-Age", "3600"); + response.setHeader("Access-Control-Allow-Headers", "Authorization"); + response.setHeader("Access-Control-Allow-Credentials", "true"); + return true; + } + +} \ No newline at end of file diff --git a/src/main/java/cn/stylefeng/guns/config/web/SpringMvcConfiguration.java b/src/main/java/cn/stylefeng/guns/config/web/SpringMvcConfiguration.java index 8370f2c9..27b437b8 100644 --- a/src/main/java/cn/stylefeng/guns/config/web/SpringMvcConfiguration.java +++ b/src/main/java/cn/stylefeng/guns/config/web/SpringMvcConfiguration.java @@ -32,6 +32,9 @@ public class SpringMvcConfiguration implements WebMvcConfigurer { @Resource private PermissionSecurityInterceptor permissionSecurityInterceptor; + @Resource + private OptionsSecurityInterceptor optionsSecurityInterceptor; + /** * 重写系统的默认错误提示 * @@ -78,6 +81,7 @@ public class SpringMvcConfiguration implements WebMvcConfigurer { public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(authJwtTokenSecurityInterceptor); registry.addInterceptor(permissionSecurityInterceptor); + registry.addInterceptor(optionsSecurityInterceptor); } /**