提交 | 用户 | 时间
|
e7c126
|
1 |
package com.iailab.gateway.filter.cors; |
H |
2 |
|
|
3 |
import org.springframework.cloud.gateway.filter.GatewayFilterChain; |
|
4 |
import org.springframework.cloud.gateway.filter.GlobalFilter; |
|
5 |
import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter; |
|
6 |
import org.springframework.core.Ordered; |
|
7 |
import org.springframework.http.HttpHeaders; |
|
8 |
import org.springframework.stereotype.Component; |
|
9 |
import org.springframework.web.server.ServerWebExchange; |
|
10 |
import reactor.core.publisher.Mono; |
|
11 |
|
|
12 |
import java.util.ArrayList; |
|
13 |
|
|
14 |
/** |
|
15 |
* 解决 Spring Cloud Gateway 2.x 跨域时,出现重复 Origin 的 BUG |
|
16 |
* |
|
17 |
* 参考文档:<a href="https://blog.csdn.net/zimou5581/article/details/90043178" /> |
|
18 |
* |
|
19 |
* @author iailab |
|
20 |
*/ |
|
21 |
@Component |
|
22 |
public class CorsResponseHeaderFilter implements GlobalFilter, Ordered { |
|
23 |
|
|
24 |
@Override |
|
25 |
public int getOrder() { |
|
26 |
// 指定此过滤器位于 NettyWriteResponseFilter 之后 |
|
27 |
// 即待处理完响应体后接着处理响应头 |
|
28 |
return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER + 1; |
|
29 |
} |
|
30 |
|
|
31 |
@Override |
|
32 |
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { |
|
33 |
return chain.filter(exchange).then(Mono.defer(() -> { |
|
34 |
exchange.getResponse().getHeaders().entrySet().stream() |
|
35 |
.filter(kv -> (kv.getValue() != null && kv.getValue().size() > 1)) |
|
36 |
.filter(kv -> (kv.getKey().equals(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN) |
|
37 |
|| kv.getKey().equals(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS))) |
|
38 |
.forEach(kv -> kv.setValue(new ArrayList<String>() {{ |
|
39 |
add(kv.getValue().get(0)); |
|
40 |
}})); |
|
41 |
return chain.filter(exchange); |
|
42 |
})); |
|
43 |
} |
|
44 |
|
|
45 |
} |