CORS的预检请求使用OPTIONS
不带凭据的HTTP ,请参阅跨域资源共享:
否则,请发出预检请求。使用方法OPTIONS和以下附加约束,使用引荐来源来源作为覆盖引荐来源,并设置了手动重定向标志和块cookie标志,从起源来源起点获取请求URL:
你必须允许HTTP匿名访问OPTIONS。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.andMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/login").permitAll()
.anyRequest().fullyAuthenticated()
.and()
.httpBasic()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf().disable();
}
从Spring Security 4.2.0开始,你可以使用内置支持,请参阅Spring Security Reference:
Spring Framework为CORS提供了一流的支持。必须在Spring Security之前处理CORS,因为飞行前请求将不包含任何cookie(即JSESSIONID
)。如果请求不包含任何cookie,并且首先使用Spring Security,则该请求将确定用户未通过身份验证(因为请求中没有cookie),并拒绝该用户。
确保首先处理CORS的最简单方法是使用CorsFilter
。用户可以CorsFilter
通过CorsConfigurationSource
使用以下命令将集成到Spring Security中:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// by default uses a Bean by the name of corsConfigurationSource
.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;
}
}