cors配置

This commit is contained in:
litianxiang
2026-05-05 16:33:52 +08:00
parent b697d86fef
commit 8e2ba26fa7

View File

@@ -0,0 +1,71 @@
package com.aida.gateway.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import java.util.Arrays;
import java.util.List;
@Configuration
public class CorsConfig {
private static final List<String> ALLOWED_HEADERS = Arrays.asList(
"Origin", "Content-Type", "Accept", "Authorization",
"X-Requested-With", "Access-Control-Request-Method",
"Access-Control-Request-Headers"
);
private static final List<String> ALLOWED_METHODS = Arrays.asList(
HttpMethod.GET.name(), HttpMethod.POST.name(),
HttpMethod.PUT.name(), HttpMethod.DELETE.name(),
HttpMethod.OPTIONS.name(), HttpMethod.PATCH.name()
);
private static final long MAX_AGE = 3600L;
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public WebFilter corsWebFilter() {
return (ServerWebExchange exchange, WebFilterChain chain) -> {
ServerHttpRequest request = exchange.getRequest();
if (!CorsUtils.isCorsRequest(request)) {
return chain.filter(exchange);
}
ServerHttpResponse response = exchange.getResponse();
HttpHeaders headers = response.getHeaders();
String origin = request.getHeaders().getOrigin();
if (origin == null || origin.isEmpty()) {
origin = "*";
}
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, String.join(",", ALLOWED_METHODS));
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, String.join(",", ALLOWED_HEADERS));
headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, String.join(",", ALLOWED_HEADERS));
headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, String.valueOf(MAX_AGE));
if (CorsUtils.isPreFlightRequest(request)) {
response.setStatusCode(HttpStatus.OK);
return Mono.empty();
}
return chain.filter(exchange);
};
}
}