更新时间:2022-06-25 03:54:02
CORS的预检请求使用不带凭据的HTTP OPTIONS
,请参见
CORS' preflight request uses HTTP OPTIONS
without credentials, see Cross-Origin Resource Sharing:
否则,请发出预检请求.使用引荐来源作为覆盖引荐来源,并使用方法OPTIONS并设置以下附加约束,将引荐来源作为覆盖引荐来源,从来源来源开始获取请求URL:
Otherwise, make a preflight request. Fetch the request URL from origin source origin using referrer source as override referrer source with the manual redirect flag and the block cookies flag set, using the method OPTIONS, and with the following additional constraints:
您必须允许HTTP OPTIONS
的匿名访问.
You have to allow anonymous access for HTTP OPTIONS
.
您修改(简化)的代码:
Your modified (and simplified) code:
@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开始,您可以使用内置支持,请参见
Since Spring Security 4.2.0 you can use the built-in support, see Spring Security Reference:
19. CORS
Spring框架为CORS提供了一流的支持.必须在Spring Security之前处理CORS,因为飞行前请求将不包含任何cookie(即JSESSIONID
).如果请求中不包含任何cookie,并且首先使用Spring Security,则该请求将确定用户未通过身份验证(因为请求中没有cookie),并拒绝该用户.
Spring Framework provides first class support for CORS. CORS must be processed before Spring Security because the pre-flight request will not contain any cookies (i.e. the JSESSIONID
). If the request does not contain any cookies and Spring Security is first, the request will determine the user is not authenticated (since there are no cookies in the request) and reject it.
确保首先处理CORS的最简单方法是使用CorsFilter
.用户可以使用以下内容提供CorsConfigurationSource
来将CorsFilter
与Spring Security集成:
The easiest way to ensure that CORS is handled first is to use the CorsFilter
. Users can integrate the CorsFilter
with Spring Security by providing a CorsConfigurationSource
using the following:
@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;
}
}