SpringCloud Gateway跨域配置

young 554 2021-10-18

代码配置

@Configuration
public class CorsFilterConfiguration {

    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(Boolean.TRUE);
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }

}

yaml配置

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]': 
            # 允许携带认证信息
            # 允许跨域的源(网站域名/ip),设置*为全部
            # 允许跨域请求里的head字段,设置*为全部
            # 允许跨域的method, 默认为GET和OPTIONS,设置*为全部
            # 跨域允许的有效期
            allow-credentials: true
            allowed-origins: 
            - "http://localhost:13009"
            - "http://localhost:13010"
            allowed-headers: "*"
            allowed-methods: 
            - OPTIONS
            - GET
            - POST
            max-age: 3600
            # 允许response的head信息
            # 默认仅允许如下6个:
            #     Cache-Control
            #     Content-Language
            #     Content-Type
            #     Expires
            #     Last-Modified
            #     Pragma
            #exposed-headers: