debugjavaspringModerate
CORS errors in Spring Boot: difference between MVC config and Spring Security
Viewed 0 times
CORSpreflightOPTIONSSpring Security CORSCorsConfigurationSourceAccess-Control-Allow-Origin
Error Messages
Problem
Configuring CORS via WebMvcConfigurer works for endpoints not protected by Spring Security, but CORS preflight OPTIONS requests to secured endpoints return 401 or 403 before the CORS headers are added, causing the browser to block the request.
Solution
Configure CORS at the Spring Security level so it fires before authentication:
Alternatively, use @CrossOrigin on individual controllers for simpler cases without security.
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
// ... rest of config
return http.build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://app.example.com"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
config.setAllowedHeaders(List.of("*"));
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}Alternatively, use @CrossOrigin on individual controllers for simpler cases without security.
Why
Spring Security's filter chain runs before Spring MVC. CORS preflight OPTIONS requests are intercepted and rejected by the security filter before the MVC CORS configuration can add the required response headers.
Gotchas
- Never use allowedOrigins("*") with allowCredentials(true) — the spec forbids this combination and Spring will throw an exception
- @CrossOrigin annotations are processed by Spring MVC, not Spring Security — they won't help secured endpoints
- The CorsFilter bean in Spring Security replaces MvcCorsFilter; having both can cause double-header issues
Revisions (0)
No revisions yet.