From fea726f2eda31676984d5d06af468257c018aba5 Mon Sep 17 00:00:00 2001 From: Amadeus Date: Sun, 5 May 2024 22:39:48 +0800 Subject: [PATCH] =?UTF-8?q?=E8=B7=A8=E5=9F=9F=E6=89=8B=E5=8A=A8=E9=85=8D?= =?UTF-8?q?=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/example/filter/CorsFilter.java | 32 +++++++++++++++++++ src/main/java/com/example/utils/Const.java | 3 ++ src/main/resources/application.yaml | 2 ++ 3 files changed, 37 insertions(+) create mode 100644 src/main/java/com/example/filter/CorsFilter.java diff --git a/src/main/java/com/example/filter/CorsFilter.java b/src/main/java/com/example/filter/CorsFilter.java new file mode 100644 index 0000000..485a312 --- /dev/null +++ b/src/main/java/com/example/filter/CorsFilter.java @@ -0,0 +1,32 @@ +package com.example.filter; + +import com.example.utils.Const; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpFilter; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +import java.io.IOException; + + +@Component +@Order(Const.ORDER_CORS) +public class CorsFilter extends HttpFilter { + @Override + protected void doFilter(HttpServletRequest request, + HttpServletResponse response, + FilterChain chain) throws IOException, ServletException { + this.addCorsHeader(request , response); + chain.doFilter(request, response); + } + + private void addCorsHeader(HttpServletRequest request, + HttpServletResponse response){ + response.addHeader("Access-Control-Allow-Origin" , request.getHeader("Origin")); + response.addHeader("Access-Control-Allow-Methods", "GET , POST , PUT, DELETE , OPTIONS"); + response.addHeader("Access-Control-Allow-Headers", "Authorization , Content-Type "); + } +} diff --git a/src/main/java/com/example/utils/Const.java b/src/main/java/com/example/utils/Const.java index 09193a8..1d743e2 100644 --- a/src/main/java/com/example/utils/Const.java +++ b/src/main/java/com/example/utils/Const.java @@ -2,4 +2,7 @@ package com.example.utils; public class Const { public static final String JWT_BLACK_LIST = "jwt:blacklist:"; + + public static final int ORDER_CORS = -102; + } diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 74f9ef0..b2617ed 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -1,6 +1,8 @@ spring: security: + filter: + order: -100 #默认值为-100 jwt: key: abcdefgh expire: 7