同源策略

This commit is contained in:
sxu 2025-04-17 15:52:03 +08:00
parent 4017b7c9d4
commit 0aef68c096
1 changed files with 33 additions and 0 deletions

View File

@ -0,0 +1,33 @@
package com.bonus.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;
/**
* Description 全局跨域配置
*/
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsWebFilter corsFilter() {
// 创建一个新的CorsConfiguration对象用于配置跨域请求
CorsConfiguration config = new CorsConfiguration();
// 允许所有的HTTP请求方法GET, POST, PUT, DELETE等
config.addAllowedMethod("*");
// 允许所有的域名发起的请求 比如http://localhost:8080
config.addAllowedOrigin("*");
// 允许所有的域名发起的请求支持正则表达式 比如http://localhost:8080
config.addAllowedOriginPattern("*");
// 允许所有的请求头部信息 比如tokenContent-Type
config.addAllowedHeader("*");
// 创建一个UrlBasedCorsConfigurationSource对象并使用PathPatternParser进行路径匹配
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
// 注册跨域配置应用于所有的URL路径
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}