问题
在Spring Cloud项目中,前后端分离目前很常见,在调试时,会遇到两种情况的跨域:
前端页面通过不同域名或IP访问微服务的后台,例如前端人员会在本地起HttpServer 直连后台开发本地起的服务,此时,如果不加任何配置,前端页面的请求会被浏览器跨域限制拦截,所以,业务服务常常会添加如下代码设置全局跨域:
@Bean
public CorsFilter corsFilter() {
logger.debug("CORS限制打开");
CorsConfiguration config = new CorsConfiguration();
# 仅在开发环境设置为*
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
return new CorsFilter(configSource);
}
前端页面通过不同域名或IP访问SpringCloud Gateway,例如前端人员在本地起HttpServer直连服务器的Gateway进行调试。此时,同样会遇到跨域。需要在Gateway的配置文件中增加:
spring:
cloud:
gateway:
globalcors:
cors-configurations:
# 仅在开发环境设置为*
'[/**]':
allowedOrigins: "*"
allowedHeaders: "*"
allowedMethods: "*"
那么,此时直连微服务和网关的跨域问题都解决了,是不是很完美?
Spring Cloud 教程推荐:https://www.javastack.cn/categories/Spring-Cloud/
No~ 问题来了,前端仍然会报错:“不允许有多个’Access-Control-Allow-Origin’ CORS头”。
Access to XMLHttpRequest at 'http://192.168.2.137:8088/api/two' from origin 'http://localhost:3200' has been blocked by CORS policy:
The 'Access-Control-Allow-Origin' header contains multiple values '*, http://localhost:3200', but only one is allowed.
仔细查看返回的响应头,里面包含了两份Access-Control-Allow-Origin头。
我们用客户端版的PostMan做一个模拟,在请求里设置头:Origin : *
,查看返回结果的头:
不能用Chrome插件版,由于浏览器的限制,插件版设置Origin的Header是无效的
发现问题了:
Vary
和 Access-Control-Allow-Origin
两个头重复了两次,其中浏览器对后者有唯一性限制!
分析
Spring Cloud Gateway是基于SpringWebFlux
的,所有web请求首先是交给DispatcherHandler
进行处理的,将HTTP请求交给具体注册的handler去处理。
我们知道Spring Cloud Gateway进行请求转发,是在配置文件里配置路由信息,一般都是用url predicates模式,对应的就是RoutePredicateHandlerMapping
。所以,DispatcherHandler
会把请求交给 RoutePredicateHandlerMapping.
那么,接下来看下 RoutePredicateHandlerMapping.getHandler(ServerWebExchange exchange)
方法,默认提供者是其父类 AbstractHandlerMapping
:
@Override
public Mono<Object> getHandler(ServerWebExchange exchange) {
return getHandlerInternal(exchange).map(handler -> {
if (logger.isDebugEnabled()) {
logger.debug(exchange.getLogPrefix() + "Mapped to " + handler);
}
ServerHttpRequest request = exchange.getRequest();
// 可以看到是在这一行就进行CORS判断,两个条件:
// 1. 是否配置了CORS,如果不配的话,默认是返回false的
// 2. 或者当前请求是OPTIONS请求,且头里包含ORIGIN和ACCESS_CONTROL_REQUEST_METHOD
if (hasCorsConfigurationSource(handler) || CorsUtils.isPreFlightRequest(request)) {
CorsConfiguration config = (this.corsConfigurationSource != null ? this.corsConfigurationSource.getCorsConfiguration(exchange) : null);
CorsConfiguration handlerConfig = getCorsConfiguration(handler, exchange);
config = (config != null ? config.combine(handlerConfig) : handlerConfig);
//此处交给DefaultCorsProcessor去处理了
if (!this.corsProcessor.process(config, exchange) || CorsUtils.isPreFlightRequest(request)) {
return REQUEST_HANDLED_HANDLER;
}
}
return handler;
});
}
注:
网上有些关于修改Gateway的CORS设定的方式,是跟前面SpringBoot一样,实现一个
CorsWebFilter
的Bean,靠写代码提供CorsConfiguration
,而不是修改Gateway的配置文件。其实本质,都是将配置交给corsProcessor去处理,殊途同归。但靠配置解决永远比hard code来的优雅。
该方法把Gateway里定义的所有的 GlobalFilter
加载进来,作为handler返回,但在返回前,先进行