我在将 Spring Security 添加到 Spring Gateway 应用程序时遇到问题。我不知道它是否相关,但我正在使用 spring-boot-starter-parent 2.5.8。
我最初在没有 spring security 的情况下创建了网关应用程序,以测试路由是否可以使用它的 eureka url 到另一个 api。这很好用。使用此配置收到 200 响应:
@Configuration
public class RouterConfig {
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
return builder.routes()
.route("account", r -> r
.path("/account/**")
.filters(f -> f.stripPrefix(1).prefixPath("/java-app-account/v1"))
.uri("lb://JAVA-APP-ACCOUNT")
)
.build();
}
}
因此,当我添加 Spring Boot 安全性时,显然 CORS 会出现 403 禁止错误,因此我添加了以下配置:
@Configuration
@EnableConfigurationProperties(value = {GlobalCorsProperties.class})
public class SpringSecurityConfig {
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) throws Exception {
http
.authorizeExchange()
.pathMatchers(HttpMethod.OPTIONS,"/account/**").permitAll()
.pathMatchers(HttpMethod.POST,"/account/**").permitAll()
;
return http.build();
}
}
和
public class CustomCorsConfiguration {
@Bean
public WebFilter corsFilter() {
return (ServerWebExchange ctx, WebFilterChain chain) -> {
ServerHttpRequest request = ctx.getRequest();
if (CorsUtils.isCorsRequest(request)) {
ServerHttpResponse response = ctx.getResponse();
HttpHeaders headers = response.getHeaders();
headers.add("Access-Control-Allow-Origin", "http://localhost:4200");
headers.add("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS, PATCH");
headers.add("Access-Control-Max-Age", "7200");
headers.add("Access-Control-Allow-Headers",
"x-requested-with, authorization, Content-Type, Content-Length, Authorization, credential, X-XSRF-TOKEN");
if (request.getMethod() == HttpMethod.OPTIONS) {
response.setStatusCode(HttpStatus.OK);
return Mono.empty();
}
}
return chain.filter(ctx);
};
}
}
我遇到的问题是,预检 OPTIONS 请求返回标头 Access-Control-Allow-Headers,但 POST 被拒绝并出现 Forbidden 错误,响应中没有标头。
我在这里错过了什么?
CSRF 过滤器在 CORS 过滤器能够添加标头之前停止请求。禁用 CSRF 保护可以解决该问题。我将添加 CSRF 保护并确保令牌现在已通过。