CORS

Fix CORS Error in Spring Boot — Java Backend

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 →