提交 | 用户 | 时间
|
e7c126
|
1 |
package com.iailab.gateway.filter.cors; |
H |
2 |
|
|
3 |
import org.springframework.http.HttpHeaders; |
|
4 |
import org.springframework.http.HttpMethod; |
|
5 |
import org.springframework.http.HttpStatus; |
|
6 |
import org.springframework.http.server.reactive.ServerHttpRequest; |
|
7 |
import org.springframework.http.server.reactive.ServerHttpResponse; |
|
8 |
import org.springframework.stereotype.Component; |
|
9 |
import org.springframework.web.cors.reactive.CorsUtils; |
|
10 |
import org.springframework.web.server.ServerWebExchange; |
|
11 |
import org.springframework.web.server.WebFilter; |
|
12 |
import org.springframework.web.server.WebFilterChain; |
|
13 |
import reactor.core.publisher.Mono; |
|
14 |
|
|
15 |
/** |
|
16 |
* 跨域 Filter |
|
17 |
* |
|
18 |
* @author iailab |
|
19 |
*/ |
|
20 |
@Component |
|
21 |
public class CorsFilter implements WebFilter { |
|
22 |
|
|
23 |
private static final String ALL = "*"; |
|
24 |
private static final String MAX_AGE = "3600L"; |
|
25 |
|
|
26 |
@Override |
|
27 |
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { |
|
28 |
// 非跨域请求,直接放行 |
|
29 |
ServerHttpRequest request = exchange.getRequest(); |
|
30 |
if (!CorsUtils.isCorsRequest(request)) { |
|
31 |
return chain.filter(exchange); |
|
32 |
} |
|
33 |
|
|
34 |
// 设置跨域响应头 |
|
35 |
ServerHttpResponse response = exchange.getResponse(); |
|
36 |
HttpHeaders headers = response.getHeaders(); |
|
37 |
headers.add("Access-Control-Allow-Origin", ALL); |
|
38 |
headers.add("Access-Control-Allow-Methods", ALL); |
|
39 |
headers.add("Access-Control-Allow-Headers", ALL); |
|
40 |
headers.add("Access-Control-Max-Age", MAX_AGE); |
|
41 |
if (request.getMethod() == HttpMethod.OPTIONS) { |
|
42 |
response.setStatusCode(HttpStatus.OK); |
|
43 |
return Mono.empty(); |
|
44 |
} |
|
45 |
return chain.filter(exchange); |
|
46 |
} |
|
47 |
|
|
48 |
} |