spring cloud gateway请求跨域问题解决方案

网友投稿 857 2023-06-30

spring cloud gateway请求跨域问题解决方案

spring cloud gateway请求跨域问题解决方案

这篇文章主要介绍了spring cloud gateway请求跨域问题解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

代码如下

@Configuration

public class CorsConfig implements GlobalFilter, Ordered {

private static final String ALL = "*";

private static final String MAX_AGE = "18000L";

@Bean

public RouteDefinitionLocator discoveryClientRouteDefinitionLocator(DiscoveryClient discoveryClient,

DiscoveryLocatorProperties prophttp://erties) {

return new DiscoveryClientRouteDefinitionLocator(discoveryClient, properties);

}

@Bean

public ServerCodecConfigurer serverCodecConfigurer() {

return new DefaultServerCodecConfigurer();

}

   //添加请求头 

@Bean

public WebFilter corsFilter() {

returnhttp:// (ServerWebExchange ctx, WebFilterChain chain) -> {

ServerHttpRequest request = ctx.getRequest();

if (!CorsUtils.isCorsRequest(request)) {

return chain.filter(ctx);

}

HttpHeaders requestHeaders = request.getHeaders();

ServerHttpResponse response = ctx.getResponse();

HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod();

HttpHeaders headers = response.getHeaders();

headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());

headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders.getAccessControlRequestHeaders());

if (requestMethod != null) {

headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name());

}

headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");

headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, ALL);

headershttp://.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);

if (request.getMethod() == HttpMethod.OPTIONS) {

response.setStatusCode(HttpStatus.OK);

return Mono.empty();

}

return chain.filter(ctx);

};

}

  //将请求头中有多个值的去掉 这是该版本的一个bug

@Override

public Mono 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)

|| khttp://v.getKey().equals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS)))

.forEach(kv -> {

kv.setValue(new ArrayList() {{

add(kv.getValue().get(0));

}});

});

return chain.filter(exchange);

}));

}

@Override

public int getOrder() {

// 指定此过滤器位于NettyWriteResponseFilter之后

// 即待处理完响应体后接着处理响应头

return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER + 1;

}

}

此处的spring-cloud-gateway的版本是2.1.3.RELEASE

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:详解基于MVC的数据查询模块进行模糊查询
下一篇:基于SpringBoot整合oauth2实现token认证
相关文章

 发表评论

暂时没有评论,来抢沙发吧~