Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Spring Boot global CORS configuration has no effect, but @CrossOrigin works

ErrorNo 'Access-Control-Allow-Origin' header is present on the requested resource.

Short answer

Spring checks CORS only after it maps a request to a handler, and only against a configuration that matches that request. When a global setup does nothing, check that the WebMvcConfigurer is a registered bean, that the pattern covers the URL, that the URL really reaches a controller, and that the app is not WebFlux or an Actuator endpoint.

  • Applies to Spring Boot 4, Spring Framework 7, Spring MVC and Spring WebFlux
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Call the URL once as a plain request to see its real status, then again with an Origin header, the way a browser sends it. A 404 on the plain call means the problem is the URL. A 200 with no Access-Control headers on the second call means no CORS configuration matches the request.

    curl -i http://localhost:8080/api/orders
    
    curl -i http://localhost:8080/api/orders \
      -H "Origin: http://localhost:5173"
  2. 2Match what you see, then jump to its fix

    1. 1No response from the app carries CORS headers, and a log line or breakpoint inside addCorsMappings is never reachedThe WebMvcConfigurer is not registered as a beanFix
    2. 2CORS works for one path prefix, for example /api/orders, and not for another such as /v2/orders or /healthThe mapping pattern does not cover the URL being calledFix
    3. 3The plain request from the first step returns 404, and the browser still reports a CORS failureThe request never reaches a controller, so CORS is never evaluatedFix
    4. 4GET and POST pass, PUT, PATCH and DELETE fail at the preflight, and the same method works on a controller with @CrossOriginGlobal defaults allow only GET, HEAD and POSTFix
    5. 5The project depends on spring-boot-starter-webflux, and the CORS class was copied from a Spring MVC exampleThe application is reactive and needs the WebFlux configurationFix
    6. 6Your own /api calls work from the browser, but a call to /actuator/health or another Actuator endpoint is blockedThe blocked call goes to an Actuator endpointFix

What does the error look like?

  • No 'Access-Control-Allow-Origin' header is present on the requested resource.
  • The preflight OPTIONS request has no Access-Control headers, and a controller annotated with @CrossOrigin on the same app answers correctly
  • CORS error in the browser console, while the Network tab shows 404 for the same URL

Cause 1 of 6

The WebMvcConfigurer is not registered as a bean

1Check

Spring Boot takes global CORS rules from a WebMvcConfigurer bean. A class that implements the interface but is not registered as a bean is never called. Search for the class and its annotations.

grep -rn -B3 "WebMvcConfigurer" src/main/java

2Fix

Register it: annotate the class with @Configuration, or expose the configurer from a @Bean method. Keep @EnableWebMvc off unless you want to replace Boot's MVC defaults.

@Configuration(proxyBeanMethods = false)
public class CorsConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                        .allowedOrigins("http://localhost:5173");
            }
        };
    }
}

3Verify

Restart the app and repeat the second request from the first step; Access-Control-Allow-Origin should appear.

curl -i http://localhost:8080/api/orders -H "Origin: http://localhost:5173"

Confirmed by docs.spring.io

Did this fix it?

Cause 2 of 6

The mapping pattern does not cover the URL being called

1Check

A global configuration is a set of URL patterns, and Spring applies a mapping only to requests whose path matches its pattern. Compare each addMapping pattern with the path in the browser's Network tab.

grep -rn "addMapping" src/main/java

2Fix

Add a mapping for each prefix that browsers call, or use /** for everything.

registry.addMapping("/api/**").allowedOrigins("http://localhost:5173");
registry.addMapping("/v2/**").allowedOrigins("http://localhost:5173");

3Verify

Request a URL from each prefix with an Origin header and look for the header.

curl -is http://localhost:8080/v2/orders -H "Origin: http://localhost:5173" | grep -i access-control

Confirmed by docs.spring.io

Did this fix it?

Cause 3 of 6

The request never reaches a controller, so CORS is never evaluated

1Check

Spring looks at the CORS configuration only after a request has been mapped to a handler. If no matching configuration is found, it adds no CORS headers, and the browser rejects the response. A mistyped path therefore looks like a CORS problem.

curl -i -X POST http://localhost:8080/api/orders -H "Content-Type: application/json" -d '{}'

2Fix

Fix the URL or the mapping first. Make the path and HTTP method in the controller match what the front end calls.

@RestController
@RequestMapping("/api/orders")
class OrderController {
    @PostMapping
    Order create(@RequestBody OrderRequest body) { /* ... */ }
}

3Verify

The plain request now returns a normal status, and the request with an Origin header carries the CORS headers.

curl -i -X POST http://localhost:8080/api/orders -H "Origin: http://localhost:5173" -H "Content-Type: application/json" -d '{}'

Confirmed by docs.spring.io

Did this fix it?

Cause 4 of 6

Global defaults allow only GET, HEAD and POST

1Check

A global mapping allows all origins and headers, but only the GET, HEAD and POST methods unless you list more. @CrossOrigin instead allows the methods its handler is mapped to, which is why it seems to work.

curl -i -X OPTIONS http://localhost:8080/api/orders/7 -H "Origin: http://localhost:5173" -H "Access-Control-Request-Method: DELETE"

2Fix

List the methods in the global mapping. Global and local rules are combined: origins add up, and the local value wins for allowCredentials and maxAge.

registry.addMapping("/api/**")
        .allowedOrigins("http://localhost:5173")
        .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE");

3Verify

The DELETE preflight now answers with the method in Access-Control-Allow-Methods.

curl -is -X OPTIONS http://localhost:8080/api/orders/7 -H "Origin: http://localhost:5173" -H "Access-Control-Request-Method: DELETE" | grep -i access-control

Confirmed by docs.spring.io

Did this fix it?

Cause 5 of 6

The application is reactive and needs the WebFlux configuration

1Check

Spring WebFlux has its own configuration interface and its own filter. A WebMvcConfigurer written for Spring MVC is the wrong API for it. Check which starter the project uses.

grep -n "starter-web\|starter-webflux" pom.xml build.gradle build.gradle.kts 2>/dev/null

2Fix

Implement WebFluxConfigurer, or declare a CorsWebFilter bean.

@Configuration
public class WebFluxCors implements WebFluxConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:5173")
                .allowedMethods("GET", "POST", "PUT", "DELETE");
    }
}

3Verify

Request a reactive endpoint with an Origin header; the CORS headers should be in the response.

curl -is http://localhost:8080/api/orders -H "Origin: http://localhost:5173" | grep -i access-control

Confirmed by docs.spring.io

Did this fix it?

Cause 6 of 6

The blocked call goes to an Actuator endpoint

1Check

Actuator's web endpoints have their own CORS switch, and it is off by default. It turns on only when management.endpoints.web.cors.allowed-origins is set.

grep -rn "management.endpoints.web.cors" src/main/resources

2Fix

Set the origins, and the methods you need, in the Actuator properties.

management:
  endpoints:
    web:
      cors:
        allowed-origins: "http://localhost:5173"
        allowed-methods: "GET,POST"

3Verify

Call an Actuator URL with an Origin header and read the response headers.

curl -is http://localhost:8080/actuator/health -H "Origin: http://localhost:5173" | grep -i access-control

Confirmed by docs.spring.io

Did this fix it?

How do I stop it coming back?

  • Keep one CORS class for the application, and log or test that it loads at start-up.
  • Choose either global mapping or @CrossOrigin as the main style, so the combined result is easy to predict.
  • Always check the plain status of a URL before blaming CORS: a 404 or 500 shows up as a CORS error in the console.
  • Keep the allowed origins in configuration properties, one set per environment.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

Spring returns 403 with the body 'Invalid CORS request'

403 Forbidden on the OPTIONS request

Spring MVC answers 403 with the text Invalid CORS request when a cross-origin request fails one of its CORS checks: the origin, the method or a header is not allowed by your configuration.

4 causes, each with a fix

Web apps

The browser blocks your API response: no Access-Control-Allow-Origin header

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.example.com/orders. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

The browser received the response but refused to hand it to your script, because it did not carry an Access-Control-Allow-Origin header naming the page's origin.

4 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.