Gateway跨域
定义全局配置类CorsConfig
/**
* @Author: LailaiMonkey
* @Description:
* @Date:Created in 2020-08-28 13:45
* @Modified By:
*/
@Configuration
public class CorsConfig implements GlobalFilter, Ordered {
@Override
public int getOrder() {
// 指定此过滤器位于NettyWriteResponseFilter之后
// 即待处理完响应体后接着处理响应头
return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER + 1;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return chain.filter(exchange).then(Mono.defer(() -> {
exchange.getResponse().getHeaders().entrySet().stream()
.filter(kv -> (kv.getValue() != null && kv.getValue().size() > 1))
.filter(kv -> (kv.getKey().equals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)
|| kv.getKey().equals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)))
.forEach(kv -> {
kv.setValue(new ArrayList<String>() {
{
add(kv.getValue().get(0));
}});
});
return chain.filter(exchange);
}));
}
@Bean
public RouteDefinitionLocator discoveryClientRouteDefinitionLocator(DiscoveryClient discoveryClient,
DiscoveryLocatorProperties properties) {
return new DiscoveryClientRouteDefinitionLocator(discoveryClient, properties);
}
@Bean
public ServerCodecConfigurer serverCodecConfigurer() {
return new DefaultServerCodecConfigurer();
}
@Bean
public WebFilter corsFilter() {
return (ServerWebExchange ctx, WebFilterChain chain) -> {
ServerHttpRequest request = ctx.getRequest();
if (!CorsUtils.isCorsRequest(request)) {
return chain.filter(ctx);
}
HttpHeaders requestHeaders = request.getHeaders();
String originHeader = requestHeaders.getOrigin();
ServerHttpResponse response = ctx.getResponse();
HttpHeaders headers = response.getHeaders();
if (originHeader != null) {
//设置header值
headers.setAccessControlAllowCredentials(true);
headers.setAccessControlAllowOrigin(originHeader);
headers.setAccessControlAllowMethods(Arrays.asList(HttpMethod.POST, HttpMethod.GET, HttpMethod.OPTIONS, HttpMethod.DELETE, HttpMethod.PUT));
headers.setAccessControlMaxAge(3600);
//添加header值
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
}
return chain.filter(ctx);
};
}
}
Gateway版本:2.1.0.RELEASE,如有好的方法评论链接!!!
来源:oschina
链接:https://my.oschina.net/u/4397965/blog/4814613