feat: 添加网关
This commit is contained in:
@@ -16,5 +16,10 @@
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -0,0 +1,68 @@
|
||||
package cn.meowrain.aioj.backend.gateway.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.reactive.CorsWebFilter;
|
||||
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
|
||||
import org.springframework.web.util.pattern.PathPatternParser;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 全局 CORS 配置(WebFlux 环境使用 CorsWebFilter)
|
||||
*
|
||||
* WebFlux 不使用 Spring MVC 的 CorsFilter,
|
||||
* 而是使用专门的 CorsWebFilter 处理跨域。
|
||||
*
|
||||
* 此配置实现了:
|
||||
* - 允许任意域名访问(AllowedOriginPatterns = "*")
|
||||
* - 允许所有请求方法(GET、POST、PUT...)
|
||||
* - 允许所有请求头
|
||||
* - 允许跨域携带 Cookie(AllowCredentials)
|
||||
* - 对所有路径生效(/**)
|
||||
*/
|
||||
@Configuration
|
||||
public class CorsConfig {
|
||||
|
||||
/**
|
||||
* 注册全局 CORS 过滤器
|
||||
*
|
||||
* @return CorsWebFilter 跨域过滤器
|
||||
*/
|
||||
@Bean
|
||||
public CorsWebFilter corsWebFilter() {
|
||||
|
||||
// 创建跨域配置对象
|
||||
CorsConfiguration corsConfiguration = new CorsConfiguration();
|
||||
|
||||
// 允许所有请求方式:GET、POST、PUT、DELETE、OPTIONS...
|
||||
corsConfiguration.addAllowedMethod("*");
|
||||
|
||||
// 是否允许携带 Cookie 信息。跨域默认不允许,需要显式开启
|
||||
corsConfiguration.setAllowCredentials(true);
|
||||
|
||||
/**
|
||||
* 允许跨域的来源域名
|
||||
* 使用 setAllowedOriginPatterns("*") 是 WebFlux 推荐方式,
|
||||
* 因为 setAllowedOrigins("*") 在 allowCredentials=true 时会被拦截。
|
||||
*/
|
||||
corsConfiguration.setAllowedOriginPatterns(List.of("*"));
|
||||
|
||||
// 允许所有请求头,例如 Authorization、Content-Type 等
|
||||
corsConfiguration.addAllowedHeader("*");
|
||||
|
||||
/**
|
||||
* 基于 URL 的跨域配置源,
|
||||
* PathPatternParser 用于解析路径模式(更高性能)
|
||||
*/
|
||||
UrlBasedCorsConfigurationSource source =
|
||||
new UrlBasedCorsConfigurationSource(new PathPatternParser());
|
||||
|
||||
// 对所有路径应用跨域设置
|
||||
source.registerCorsConfiguration("/**", corsConfiguration);
|
||||
|
||||
// 创建并返回 WebFlux 专用的 CORS 过滤器
|
||||
return new CorsWebFilter(source);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user