CORS
Spring Framework提供 first class support for CORS。需要在Spring Security之前处理CORS,因为预检请求不包含任何Cookie(即`JSESSIONID`)。如果请求不包含任何Cookie,并且Spring Security位于第一位,则请求将确定用户未经过身份验证(因为请求中没有Cookie)并拒绝该请求。
确保首先处理 CORS 的最简单方法是使用 CorsWebFilter
。用户可以通过提供 CorsConfigurationSource
与 Spring Security 集成 CorsWebFilter
。例如,以下操作会将 CORS 支持集成到 Spring Security 中:
-
Java
-
Kotlin
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
val configuration = CorsConfiguration()
configuration.allowedOrigins = listOf("https://example.com")
configuration.allowedMethods = listOf("GET", "POST")
val source = UrlBasedCorsConfigurationSource()
source.registerCorsConfiguration("/**", configuration)
return source
}
以下操作会禁用 Spring Security 中的 CORS 集成:
-
Java
-
Kotlin
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
// ...
.cors(cors -> cors.disable());
return http.build();
}
@Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
// ...
cors {
disable()
}
}
}