Spring Cloud Gateway 网关跨域问题解决

0、版本说明

Spring Cloud Version:Spring Cloud 2021.0.4
Spring Cloud Gateway Version:3.1.4
Spring Boot Version:2.6.11

1、网关跨域问题说明

  关于跨域的相关原理和理论,网上有大量文章对此进行说明,因此博主在这里就不再赘述,这里仅说明对于在同一注册中心中注册的服务,网关可以通过在注册中心注册的服务名对相应请求找到对应的服务进行路由转发,因此这种情况,不存在跨域问题,但是对于一些通过Nginx反向代理到网关服务下的请求进行访问时,就存在了跨域问题,所以下面网关配置也是针对此部分问题进行解决。

2、网关跨域解决

针对网关跨域解决,这里提供两种解决方案,仅供参考,下面配置均在线上环境测试通过,关于其他版本,仅供参考!

2.1、方案一:网关注入配置类

Spring Cloud Gateway提供了跨域的配置类,然后在网关项目代码中添加一个CorsWebFilter类即可实现,关于网关提供的Cors配置类,可参看官方文档(CorsConfiguration (Spring Framework 5.0.20.RELEASE API)

@Configuration
public class GlobalCorsConfig {

    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 这里仅为了说明问题,配置为放行所有域名,生产环境请对此进行修改
        config.addAllowedOrigin("*");
        // 放行的请求头
        config.addAllowedHeader("*");
        // 放行的请求方式,主要有:GET, POST, PUT, DELETE, OPTIONS
        config.addAllowedMethod("*"); 
        // 暴露头部信息
        config.addExposedHeader("*"); 
        // 是否发送cookie
        config.setAllowCredentials(true); 
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
}

说明:

        由于spring-framework从5.3.0版本开始,关于CORS跨域配置类 CorsConfiguration 中将 addAllowedOrigin 方法名修改为 addAllowedOriginPattern(spring-framework项目对应的类信息:https://github.com/spring-projects/spring-framework/blob/v5.3.0/spring-web/src/main/java/org/springframework/web/cors/CorsConfiguration.java),所以,如果项目中 spring-framework 版本高于5.3.0,请使用如下配置类代码。

@Configuration
public class GlobalCorsConfig {

    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 这里仅为了说明问题,配置为放行所有域名,生产环境请对此进行修改
        config.addAllowedOriginPattern("*");
        // 放行的请求头
        config.addAllowedHeader("*");
        // 放行的请求方式,主要有:GET, POST, PUT, DELETE, OPTIONS
        config.addAllowedMethod("*"); 
        // 暴露头部信息
        config.addExposedHeader("*"); 
        // 是否发送cookie
        config.setAllowCredentials(true); 
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
}

2.2、方案二:网关yaml文件添加配置

Spring Cloud Gateway 也提供了可以直接通过在yaml文件中配置的方式解决跨域问题,具体的类配置可以查看源码中对应的类org.springframework.cloud.gateway.config.GlobalCorsProperties,源码地址如下:

https://github.com/spring-cloud/spring-cloud-gateway/blob/v3.1.4/spring-cloud-gateway-server/src/main/java/org/springframework/cloud/gateway/config/GlobalCorsProperties.java

网关yaml配置如下:

spring:
  cloud:
    gateway:
      # 网关全局跨域配置
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins: "*"
            allowedMethods: "*"
            allowedHeaders: "*"
            allowCredentials: true
        # 解决options请求被拦截的问题
        add-to-simple-url-handler-mapping: true

说明:

        由于spring-framework从5.3.0版本开始,关于CORS跨域配置类 CorsConfiguration 中将 allowedOrigins 变量名修改为 allowedOriginPatterns(spring-framework项目对应的类信息)所以,如果项目中 spring-framework 版本高于5.3.0,请使用如下配置代码。

spring:
  cloud:
    gateway:
      # 网关全局跨域配置
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOriginPatterns: "*"
            allowedMethods: "*"
            allowedHeaders: "*"
            allowCredentials: true
        # 解决options请求被拦截的问题
        add-to-simple-url-handler-mapping: true

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Cloud GatewaySpring Cloud生态圈中的一个API网关,它提供了一种构建微服务架构的解决方案。跨域是Web开发中常见的问题,特别是在微服务架构中,不同服务之间需要进行跨域访问。本篇文章将介绍使用Spring Cloud Gateway实现跨域的方法。 首先,需要在Spring Cloud Gateway中添加Corsconfiguration Bean,代码如下: @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("*")); configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); configuration.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization")); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } 然后,在application.yml文件中添加跨域配置,代码如下: spring: cloud: gateway: globalcors: corsConfigurations: '[/**]': allowedOrigins: "*" allowedMethods: - GET - POST - PUT - DELETE allowedHeaders: - "Content-Type" - "Authorization" allowCredentials: true maxAge: 3600 这里设置了允许的来源,方法和头部,还指定了是否允许发送cookie信息,以及最大响应时间。此外,您也可以通过使用代码配置来自定义跨域规则,具体请参考Spring Cloud Gateway官方文档。 最后,在需要进行跨域访问的路由前添加跨域过滤器,代码如下: @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes() .route("path_route", r -> r.path("/hello") .filters(f -> f.addRequestHeader("Hello", "World") .addFilter(new CrossOriginFilter())) .uri("http://localhost:8081")) .build(); } 在这个例子中,我们将拦截/hello路由,并添加一个跨域过滤器。 总结来说,使用Spring Cloud Gateway实现跨域需要以下步骤:添加Corsconfiguration Bean,配置application.yml文件,添加跨域过滤器。这样,在微服务架构中实现跨域问题就变得容易了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值