Reputation: 87
So as the title mentions, I have a spring boot backend that serves a REST API to a React front end. I have been getting numerous CORS issues, and have tried multiple methods. I am not an expert on spring-security but would really appreciate some help solving this issue.
My CORS config
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;
}
Upvotes: 0
Views: 203
Reputation: 450
Your method is not annotated with @Bean
, so I do not think Spring is automatically instantiating or injecting this configuration.
Try annotating the method with @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;
}
Upvotes: 1