Spring Gateway 跨域设置

参考这篇文章解决:https://cloud.tencent.com/developer/article/1415079

springcloud gateway用在微服务里面的时候,在开发环境里面因为要不同的端口对应不同的服务,可能会有因为端口问题造成的跨域问题,那么要通过在网关里设置跨域,因为springcloud gateway用的是webflux,所以要在webflux层设置过滤器。 代码如下:

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;
@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;
    }
}
posted @ 2020-06-05 16:46  xiaoj_wang  阅读(4300)  评论(0编辑  收藏  举报