CORS Preflight未发送到服务器



我有一个Spring Boot应用程序,它使用Spring Security和Cors过滤器。有了下面的CorsFilter,我尝试进行跨来源请求

Axios.get("http://10.0.120.11:30500/user", { withCredentials: true })
.then((data) => console.log(data));

来自托管的页面http://localhost:8080。然而,浏览器给出401。奇怪的是,浏览器没有发送任何飞行前(OPTIONS(请求。

@Configuration
@EnableWebMvc
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
List<String> list = new ArrayList<>();
list.add("*");
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedHeaders(list);
corsConfiguration.setAllowedMethods(list);
corsConfiguration.setAllowedOriginPatterns(Arrays.asList("http://localhost:8080"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf()
.disable()
.formLogin()
.disable()
.httpBasic()
.disable()
.exceptionHandling()
.authenticationEntryPoint(new LoginAuthenticationEntryPoint())
//.authenticationEntryPoint(new RestAuthenticationEntryPoint())
.and()
.authorizeRequests()
.antMatchers("/",
"/error",
"/favicon.ico",
"/**/*.png",
"/**/*.gif",
"/**/*.svg",
"/**/*.jpg",
"/**/*.html",
"/**/*.css",
"/**/*.js")
.permitAll()
.antMatchers("/login/**","/auth/**", "/oauth2/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Login()
.clientRegistrationRepository(getClientRegistrationRepository())
.authorizationEndpoint()
.authorizationRequestResolver(new CustomAuthorizationRequestResolver(getClientRegistrationRepository(),"/oauth2/authorize"))
.baseUri("/oauth2/authorize")
.authorizationRequestRepository(cookieAuthorizationRequestRepository())
.and()
.redirectionEndpoint()
.baseUri("/oauth2/callback/*")
.and()
.tokenEndpoint()
.accessTokenResponseClient(new CustomTokenResponseClient())
.and()
.userInfoEndpoint()
.userService(customOAuth2UserService)
.and()
.successHandler(oAuth2AuthenticationSuccessHandler)
.failureHandler(oAuth2AuthenticationFailureHandler);
// Add our custom Token based authentication filter
http.addFilterBefore(cookieAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}

Browser可能不想发送GET请求的飞行前请求。

此外,对于可能对服务器数据造成副作用的HTTP请求方法(特别是GET以外的HTTP方法,或具有某些MIME类型的POST(,规范要求浏览器";飞行前";该请求,用HTTP OPTIONS请求方法从服务器请求支持的方法,然后;批准";从服务器发送实际请求。

参考:跨来源资源共享(CORS(

最新更新