spring网关跨域设置
时间: 2023-09-03 18:10:37 浏览: 81
在Spring Cloud Gateway中进行跨域设置,可以通过自定义GlobalFilter来实现。下面是一个示例代码:
```java
@Component
public class CorsFilter implements GlobalFilter, Ordered {
private static final String ALLOWED_HEADERS = "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN";
private static final String ALLOWED_METHODS = "GET, PUT, POST, DELETE, OPTIONS";
private static final String ALLOWED_ORIGIN = "*";
private static final String MAX_AGE = "3600";
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
if (!CorsUtils.isCorsRequest(request)) {
return chain.filter(exchange);
}
HttpHeaders headers = request.getHeaders();
ServerHttpResponse response = exchange.getResponse();
HttpMethod requestMethod = headers.getAccessControlRequestMethod();
HttpHeaders responseHeaders = response.getHeaders();
responseHeaders.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, ALLOWED_ORIGIN);
responseHeaders.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, Arrays.asList(ALLOWED_HEADERS.split(",")));
if (requestMethod != null) {
responseHeaders.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, ALLOWED_METHODS);
}
responseHeaders.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
if (request.getMethod() == HttpMethod.OPTIONS) {
response.setStatusCode(HttpStatus.OK);
return Mono.empty();
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}
```
这个GlobalFilter实现了跨域设置,可以处理OPTIONS请求,并在响应中添加跨域相关的头信息。通过将该Filter注册到Spring容器中,即可实现全局的跨域设置。