如果 Spring Boot 項目引入 Spring Security 組件,單獨(dú)聲明 CorsConfigurationSource
Bean 并不起作用,這是由于 CORS 預(yù)檢請求不含 Session ID 而請求首先被 Spring Security 處理并拒絕導(dǎo)致的。
因此茫打,必須明確地配置 Spring Security 跨域參數(shù)以便正常處理跨域請求,下面是一個配置示例:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// cors 默認(rèn)讀取名為 corsConfigurationSource Bean 的配置
.cors().and()
...
//其它配置
}
@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;
}
}