您的位置:首页 > 编程语言 > Java开发

spring cloud Gateway 处理跨域问题

2020-03-05 13:50 1976 查看

先简单描述一下架构,项目采用前后端分离的方式,前端是nodejs来搞layui(单页版),后端采用spring cloud Alibaba,网关用的是spring cloud Gateway,然后出现了跨域问题。一开始百度我以为只需要在Controller上加上@CrossOrigin就能搞定,后来发现出现了很多问题。

问题一:

因为后端还有网关,所以如果你没有自定的headers的头信息那么是可以通过 spring cloud Gateway ,但是如果有加自定义Headers,这样就会被 spring cloud Gateway给拦截,说:跨域请求中没有自定的header
错误信息如下

考虑之后觉得应该需要在spring cloud Gateway上添加跨域配置
添加方式有许多种,这里我写出尝试过可以用的两种:
一在application.yml中添加配置

spring:
application:
name: nb-web
cloud:
nacos:
discovery:
server-addr: localhost:8848
gateway:
globalcors:
corsConfigurations:
'[/**]':
allowedHeaders: "*"
allowedOrigins: "*"
allowCredentials: true
allowedMethods:
- GET
- POST
- DELETE
- PUT
- OPTION

第二种再启动类上添加bean:

/**
* 配置跨域
* @return
*/
@Bean
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
// cookie跨域
config.setAllowCredentials(Boolean.TRUE);
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
// 配置前端js允许访问的自定义响应头
config.addExposedHeader("Authorization:");

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

return new CorsWebFilter(source);
}

这样就能解决自定义headers被拦截和跨域问题,但是这样配置紧接着下一个问题又出来了

问题二
由于跨域配置会进行叠加,举个例子你在服务一种添加了跨域配置,在spring cloud Gateway中也添加了,那这样就会产生headers重复的问题:

前端就会报错,

所以你必须要进行header去重,具体办法如下:在spring cloud Gateway的过滤器中添加过滤配置

spring:
application:
name: nb-web
cloud:
nacos:
discovery:
server-addr: localhost:8848
gateway:
default-filters:
- DedupeResponseHeader=Vary Access-Control-Allow-Credentials Access-Control-Allow-Origin, RETAIN_UNIQUE
- DedupeResponseHeader=Access-Control-Allow-Origin, RETAIN_FIRST

这样就能把重复的header给去掉了,spring cloud Gateway过滤器的详细内容可以参考

https://www.imooc.com/article/290816

这样跨域问题基本就能解决了,但是因为我这边需要进行session共享,所以需要给前端传入cookie,那么问题又来了,后端配置的cookie传不出去,原因有两个1:没有加上headers上面加上Access-Control-Allow-Credentials: true,这个可以在

gateway:
default-filters:
- AddResponseHeader=Access-Control-Allow-Credentials,true

添加上,还有一个就是前端的ajax上没有加上:

, xhrFields: {withCredentials: true}
, crossDomain: true

这样浏览器就能保存cookie

至此问题就能解决了。在查阅过程中我看到关于跨域配置重复问题是存在bug的,具体内容可以参考:

https://blog.csdn.net/zimou5581/article/details/90043178
  • 点赞
  • 收藏
  • 分享
  • 文章举报
jia_jia_le94 发布了3 篇原创文章 · 获赞 0 · 访问量 70 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: