Spring Boot CORS不能与React应用程序一起工作



因此,正如标题所提到的,我有一个spring引导后端,为React前端提供REST API。我已经得到了许多CORS问题,并尝试了多种方法。我不是spring-security方面的专家,但如果有人能帮助我解决这个问题,我将非常感激。

我的CORS配置

private static final String [] AUTH_WHITELIST = {
// -- Swagger UI v2
"/v2/api-docs",
"/swagger-resources",
"/swagger-resources/**",
"/configuration/ui",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**",
"/_ah/warmup",
"/ae/test",
// -- Swagger UI v3 (OpenAPI)
"/v3/api-docs/**",
"/swagger-ui/**",
// other public endpoints of your API may be appended to this array
};
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().cors().configurationSource(corsConfigurationSource()).and().authorizeRequests()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.antMatchers(AUTH_WHITELIST).permitAll()
.anyRequest().authenticated();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider,userDetailsService));
}
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
//config.setAllowedOriginPatterns(Arrays.asList("/*"));
config.setAllowedOrigins(Arrays.asList("localhost:3000"));
config.setAllowedHeaders(Arrays.asList("*"));
config.setAllowedMethods(Arrays.asList("*"));
config.setAllowCredentials(false);
source.registerCorsConfiguration("/**", config);
return source;
}

您的方法没有注释@Bean,因此我认为Spring不会自动实例化或注入此配置。

尝试用@Bean:

注释方法
@Bean
public CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Collections.singletonList("localhost:3000"));
config.setAllowedHeaders(Collections.singletonList("*"));
config.setAllowedMethods(Collections.singletonList("*"));
config.setAllowCredentials(Boolean.FALSE);
source.registerCorsConfiguration("/**", config);
return source;
}

相关内容

最新更新