(转载)Spring Cloud Gateway配置跨域,实测有效

注:本文虽为转载文章,但代码和一些文字稍有不同
原文声明:

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_40623736/article/details/110665826

gateway配置

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

网上搜了一堆,大多都是上面的这些,但是如果只进行这样的配置的话,根本不会生效,我这边的gateway是集成了oauth2进行鉴权的,最后在Spring Security官方文档上看到了这一段
https://docs.spring.io/spring-security/site/docs/current/reference/html5/#cors
在这里插入图片描述

琢磨一番加参考其他博客之后。。。

gateway添加cros跨域配置文件

CorsConfig.java

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.config.GlobalCorsProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;


@Configuration
@EnableConfigurationProperties(GlobalCorsProperties.class)
public class CorsConfig {
    
    

    @Order(Ordered.HIGHEST_PRECEDENCE)
    @RefreshScope
    @Bean
    public CorsWebFilter corsWebFilter(GlobalCorsProperties globalCorsProperties){
    
    
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        globalCorsProperties.getCorsConfigurations().forEach(source::registerCorsConfiguration);
        return new CorsWebFilter(source);
    }
}

本人实测原文的代码跨域也是有效

猜你喜欢

转载自blog.csdn.net/weixin_43810415/article/details/110820169