SpringCloudGateway跨域配置

60 阅读1分钟

今天在发布uat环境的时候,出现了网关跨域的问题。所以思考是不是因为CorsWebFilter的优先级太低了,导致先进入验签、认证等过滤器。所以在自定义的CorsWebFilter上打了断点,发现自己认知的不足。

1.SpringCloudGateway里面有2种Filter:WebFilter和GlobalFilter

2.先执行WebFilterChain再执行DefaultGatewayFilterChain

3.CorsWebFilter属于WebFilterChain,GlobalFilter属于DefaultGatewayFilterChain。

关于这一方面的源码有时间在研究,先记录一下。 至于跨域的原因是前端配置的域名错误导致的。

最后附上CorsWebFilter

/***
* @author: claude
* @date: 2022/10/13
* @description: 跨域配置
*/
@Configuration
public class CorsConfig {

   @Bean
   public CorsWebFilter corsFilter() {
       UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
       source.registerCorsConfiguration("/**", buildConfig());
       return new CorsWebFilter(source);
   }

   private CorsConfiguration buildConfig() {
       CorsConfiguration corsConfiguration = new CorsConfiguration();
       //在生产环境上最好指定域名,以免产生跨域安全问题
       corsConfiguration.addAllowedOrigin("*");
       corsConfiguration.addAllowedHeader("*");
       corsConfiguration.addAllowedMethod("*");
       return corsConfiguration;
   }
}