Fix CORS Error in Spring Boot โ Java Backend
Updated April 2026
Spring Boot blocks cross-origin requests by default. You have three options: global config via WebMvcConfigurer, per-controller via @CrossOrigin, or โ the one most people miss โ adding CORS to Spring Security's filter chain.
Browser Console Error
Access to XMLHttpRequest at 'http://localhost:8080/api/data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.Option 1 โ Global CORS config
@Configuration
public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("https://yourapp.com") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true) .maxAge(86400); }
}
Option 2 โ Per controller with @CrossOrigin
@RestController
@CrossOrigin(origins = "https://yourapp.com", allowCredentials = "true")
public class DataController { @GetMapping("/api/data") public ResponseEntity<?> getData() { return ResponseEntity.ok(Map.of("status", "ok")); }
}
Option 3 โ Spring Security (most common issue)
If you have Spring Security, it processes requests before MVC โ so WebMvcConfigurer CORS config never runs. Add CORS to your SecurityFilterChain directly:
@Configuration
@EnableWebSecurity
public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .cors(cors -> cors.configurationSource(corsConfigurationSource())) .csrf(csrf -> csrf.disable()); return http.build(); } @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(List.of("https://yourapp.com")); config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); config.setAllowedHeaders(List.of("*")); config.setAllowCredentials(true); config.setMaxAge(86400L); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; }
}
This is the fix 90% of Spring Boot + Spring Security CORS problems need. The other two options do nothing when Security is in the chain.
Test your Spring Boot CORS config โ