此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Security 6.4.1! |
CORS
Spring Framework 为 CORS 提供了一流的支持。
CORS 必须在 Spring Security 之前处理,因为飞行前请求将不包含任何 cookie(即 )。
如果请求不包含任何 cookie,并且 Spring Security 是第一个,则请求将确定用户未经过身份验证(因为请求中没有 cookie)并拒绝它。JSESSIONID
确保首先处理 CORS 的最简单方法是使用 .
用户可以通过使用以下方法提供与 Spring Security 集成:CorsFilter
CorsFilter
CorsConfigurationSource
-
Java
-
Kotlin
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// by default uses a Bean by the name of corsConfigurationSource
.cors(withDefaults())
...
return http.build();
}
@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;
}
}
@EnableWebSecurity
open class WebSecurityConfig {
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
http {
// by default uses a Bean by the name of corsConfigurationSource
cors { }
// ...
}
return http.build()
}
@Bean
open 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
}
}
或 XML 格式
<http>
<cors configuration-source-ref="corsSource"/>
...
</http>
<b:bean id="corsSource" class="org.springframework.web.cors.UrlBasedCorsConfigurationSource">
...
</b:bean>
如果你正在使用 Spring MVC 的 CORS 支持,你可以省略指定,Spring Security 将利用提供给 Spring MVC 的 CORS 配置。CorsConfigurationSource
-
Java
-
Kotlin
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// if Spring MVC is on classpath and no CorsConfigurationSource is provided,
// Spring Security will use CORS configuration provided to Spring MVC
.cors(withDefaults())
...
return http.build();
}
}
@EnableWebSecurity
open class WebSecurityConfig {
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
http {
// if Spring MVC is on classpath and no CorsConfigurationSource is provided,
// Spring Security will use CORS configuration provided to Spring MVC
cors { }
// ...
}
return http.build()
}
}
或 XML 格式
<http>
<!-- Default to Spring MVC's CORS configuration -->
<cors />
...
</http>