美文网首页
SpringCloudGateway解决跨域

SpringCloudGateway解决跨域

作者: 茶还是咖啡 | 来源:发表于2020-11-26 10:37 被阅读0次

    很久以前我写了一个关于使用springCloudGateway解决跨域的问题,https://www.jianshu.com/p/f1938b6fc44a
    那个文章确实可以解决,但是新版本的springCloudGateway提供了跨域的配置,所以我们不需要自己编写跨域配置类就可以解决跨域了。官网解决跨域的地址如下:https://docs.spring.io/spring-cloud-gateway/docs/2.2.5.RELEASE/reference/html/#cors-configuration

    我先写一个跨域解决的配置,然后分析一下哈

    spring:
      cloud:
        gateway:
          globalcors:
            cors-configurations:
              '[/**]':
                allowedOrigins: "*"
                allowedMethods: "*"
                allowedHeaders: "*"
                allowCredentials: true
    

    cros-configuration后面关联的是一个map结构,key是uri匹配的地址,value为具体的跨域对象配置。

    @ConfigurationProperties("spring.cloud.gateway.globalcors")
    public class GlobalCorsProperties {
    
        private final Map<String, CorsConfiguration> corsConfigurations = new LinkedHashMap<>();
    
        public Map<String, CorsConfiguration> getCorsConfigurations() {
            return corsConfigurations;
        }
    }
    

    springcloudgateway启动时会将跨域配置注入到SimpleUrlHandlerMapping中,所以,如果我们使用配置中心配置跨域,网关运行的时候更新跨域配置是无效的!!!

    /**
     * This is useful for PreFlight CORS requests. We can add a "global" configuration here so
     * we don't have to modify existing predicates to allow the "options" HTTP method.
     *
     */
    
    @Configuration(proxyBeanMethods = false)
    @ConditionalOnClass(SimpleUrlHandlerMapping.class)
    @ConditionalOnProperty(
            name = "spring.cloud.gateway.globalcors.add-to-simple-url-handler-mapping",
            matchIfMissing = false)
    public class SimpleUrlHandlerMappingGlobalCorsAutoConfiguration {
    
        @Autowired
        private GlobalCorsProperties globalCorsProperties;
    
        @Autowired
        private SimpleUrlHandlerMapping simpleUrlHandlerMapping;
    
        @PostConstruct
        void config() {
            simpleUrlHandlerMapping
                    .setCorsConfigurations(globalCorsProperties.getCorsConfigurations());
        }
    
    }
    

    相关文章

      网友评论

          本文标题:SpringCloudGateway解决跨域

          本文链接:https://www.haomeiwen.com/subject/gsjaiktx.html