CORS的预检请求使用
OPTIONS不带凭据的HTTP ,请参阅跨域资源共享:
否则,请发出预检请求。使用方法OPTIONS和以下附加约束,使用引荐来源来源作为覆盖引荐来源,并设置了手动重定向标志和块cookie标志,从起源来源起点获取请求URL:
- 包括一个Access-Control-Request-Method标头,并将请求方法作为标头字段值(即使是简单方法也是如此)。
- 如果作者请求标头不为空,则包含一个Access-Control-Request-Headers标头,并以字母顺序将按字母顺序排列的作者请求标头中的标头字段名的列表以逗号分隔,作为标头字段值,每个都转换为ASCII小写(即使是更多是一个简单的标题)。
- 排除作者请求标头。
- 排除用户凭据。
- 排除请求实体主体。
你必须允许HTTP匿名访问OPTIONS。
你修改(简化)的代码:
@Overrideprotected 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:
- CORS
Spring framework为CORS提供了一流的支持。必须在Spring Security之前处理CORS,因为飞行前请求将不包含任何cookie(即
JSESSIONID)。如果请求不包含任何cookie,并且首先使用Spring Security,则该请求将确定用户未通过身份验证(因为请求中没有cookie),并拒绝该用户。
确保首先处理CORS的最简单方法是使用
CorsFilter。用户可以
CorsFilter通过
CorsConfigurationSource使用以下命令将集成到Spring Security中:
@EnableWebSecuritypublic 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; }}


