Spring Cloud Gateway 解决跨域问题
���:文中的解决方案在 Spring Cloud 2021.0.4、Spring Boot 2.7.4 版本中得到验证,完美解决,其他版本可参考
请求流程如下图:通过nginx反向代理到网关,在通过网关转发到具体的服务上
关于跨域的理论百度上已经有很多,网关到其他服务主要是通过注册中心去找的服务名在进行转发,所以不存在跨域,主要是解决nginx到网关的跨域问题
方案一:网关配置类
在网关模块注入跨域配置
@Configuration public class GlobalCorsConfig { /** * 为了安全,建议只放行需要的地址(可以再yaml中定义进行映射方便扩展) */ private List sourceCors = Arrays.asList("http://localhost:8001", "http://localhost:8002", "http://localhost:8003"); private List methods = Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"); @Bean public CorsWebFilter corsWebFilter() { CorsConfiguration config = new CorsConfiguration(); // 放行原始域 if (CollectionUtils.isEmpty(sourceCors)) { config.addAllowedOrigin("*"); // 放行所有 } else { for (String sourceCor : sourceCors) { config.addAllowedOrigin(sourceCor); } } // 放行请求头 if (CollectionUtils.isEmpty(methods)) { config.addAllowedHeader("*"); // 放行所有 } else { for (String method : methods) { config.addAllowedHeader(method); } } config.setAllowCredentials(true); // 是否发送cookie config.addAllowedMethod("*"); // 放行请求方式 config.addExposedHeader("*"); // 暴露头部信息 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return new CorsWebFilter(source); } }
方案一:Gateway yaml 配置
Gateway 也提供了跨域的配置类,可以直接在yaml中进行配置,具体的类配置可以查看源码 org.springframework.cloud.gateway.config.GlobalCorsProperties
spring: cloud: gateway: globalcors: # 全局的跨域处理 add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题 corsConfigurations: '[/**]': allowedOrigins: # 允许哪些网站的跨域请求 allowedOrigins: “*” 允许所有网站 - "https://localhost:8001" - "https://localhost:8002" - "https://localhost:8003" allowedMethods: # 允许的跨域ajax的请求方式 “*” 允许所有 - "GET" - "POST" - "DELETE" - "PUT" - "OPTIONS" allowedHeaders: "*" # 允许在请求中携带的头信息 allowCredentials: true # 是否允许携带cookie maxAge: 360000 # 这次跨域检测的有效期
The End