Skip to content
javahacks.dev
Spring MVC

Fix CORS Errors in Spring Boot and Spring MVC Applications

Fix CORS errors from a browser calling a Spring Boot API by configuring allowed origins, methods and credentials, with and without Spring Security.

6 min read
Summarize in AI
Flat illustration of a controller, a service and a repository stacked above a database, with the Spring Boot, Spring, Spring Security and Apache Maven logos.

The browser console prints something like this, and the request never reaches your JavaScript:

Text
Access to fetch at 'http://localhost:8080/api/orders' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The server may have answered normally. The browser declined to hand the response to your page because the server did not say that origin is allowed. Cross-origin resource sharing is a browser rule, so the fix is a server header. The controller side is in building REST APIs with Spring MVC.

What the browser does

For a "simple" request (GET with no custom headers), the browser sends the request and checks the response headers. For anything else, such as a POST with Content-Type: application/json or an Authorization header, it first sends a preflight:

Text
OPTIONS /api/orders
Origin: http://localhost:3000
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type

The server must answer with the matching Access-Control-Allow-Origin, Access-Control-Allow-Methods and Access-Control-Allow-Headers. If the preflight fails, the real request is never sent.

Fix 1: global configuration

java
@Configuration
class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:3000", "https://app.example.test")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("Content-Type", "Authorization")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

List the origins that really need access. maxAge lets the browser cache the preflight result, so it does not repeat on every call.

Fix 2: per controller or method

@CrossOrigin(origins = "https://app.example.test") on a controller or handler applies to just that endpoint. It is handy for one public endpoint and awkward to keep consistent across many.

Fix 3: with Spring Security

When Spring Security is on the classpath, its filter chain runs before MVC. An unauthenticated preflight is rejected with 401 or 403 before the CORS mapping above is consulted. Enable CORS in the chain and supply the configuration there:

java
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
    http.cors(Customizer.withDefaults())
        .authorizeHttpRequests(a -> a.anyRequest().authenticated());
    return http.build();
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
    var config = new CorsConfiguration();
    config.setAllowedOrigins(List.of("https://app.example.test"));
    config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    config.setAllowedHeaders(List.of("Content-Type", "Authorization"));
    var source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/api/**", config);
    return source;
}

With a CorsConfigurationSource bean defined, cors(Customizer.withDefaults()) finds it. Forgetting .cors(...) is the most common cause of a CORS setup that stops working the day Spring Security arrives.

Check the preflight yourself

Shell
curl -i -X OPTIONS localhost:8080/api/orders \
  -H 'Origin: https://app.example.test' \
  -H 'Access-Control-Request-Method: POST' \
  -H 'Access-Control-Request-Headers: content-type'

A correct response has status 200 and the three Access-Control-Allow-* headers. A 403 with the text "Invalid CORS request" means the origin is not allowed. A 401 means security is rejecting the preflight.

Credentials and wildcards

If the request includes cookies or an Authorization header with credentials: 'include', the server must name the origin explicitly and set Access-Control-Allow-Credentials: true. Spring rejects a configuration that allows * together with credentials. Use allowedOriginPatterns("https://*.example.test") when you need a pattern.

See the preflight succeed and fail

CORS errors are reported by the browser, but the server decides, and curl can play the browser's part. The browser sends an OPTIONS preflight with Origin and Access-Control-Request-Method headers before a cross-origin request that is not simple. This configuration allows one origin to call /orders, on Spring Boot 4.0.9 with Spring Security on the classpath.

java
@Configuration
class CorsOn implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry r) {
        r.addMapping("/orders")
         .allowedOrigins("https://app.example.test")
         .allowedMethods("GET", "POST");
    }
}
Shell
curl -i -X OPTIONS localhost:8096/orders -H 'Origin: https://app.example.test' -H 'Access-Control-Request-Method: POST'
curl -i -X OPTIONS localhost:8096/orders -H 'Origin: https://evil.example.test' -H 'Access-Control-Request-Method: POST'
Text
HTTP/1.1 200
Access-Control-Allow-Origin: https://app.example.test
Access-Control-Allow-Methods: GET,POST
Access-Control-Max-Age: 1800

HTTP/1.1 403
Invalid CORS request

The allowed origin got 200 with the three headers a browser looks for. The other origin got a 403 with the body Invalid CORS request, and the browser console would show the familiar message that no Access-Control-Allow-Origin header is present. The server is working as configured, so the fix is to the configuration, not to the request.

The real call then also carries the header:

Text
POST /orders  Origin: https://app.example.test
HTTP/1.1 200
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: https://app.example.test

The Vary headers matter when a cache or CDN sits in front: they tell it that the response depends on the Origin, so one origin's response is not served to another.

With Spring Security, enable CORS on the security chain

The configuration above is read by Spring MVC, and Spring Security's filter chain runs first. A preflight carries no credentials, so if the security chain requires authentication for OPTIONS, it answers 401 or 403 before MVC sees it. Tell Security to apply the CORS configuration and let preflights through.

java
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
    return http
            .cors(Customizer.withDefaults())          // use the MVC CORS configuration
            .authorizeHttpRequests(a -> a.anyRequest().authenticated())
            .build();
}

With cors(withDefaults()), Security's CorsFilter handles the preflight early and returns the headers, using the mappings from WebMvcConfigurer or a CorsConfigurationSource bean. The symptom of forgetting it is a CORS error in the browser for an endpoint that works in Postman.

Credentials and wildcards

A request that sends cookies or an Authorization header with credentials: "include" cannot use Access-Control-Allow-Origin: *; the specification requires an explicit origin. Spring enforces this: allowCredentials(true) combined with allowedOrigins("*") throws at startup with a message telling you to use allowedOriginPatterns instead. Use patterns for a family of subdomains and list exact origins otherwise.

java
.allowedOriginPatterns("https://*.example.test")
.allowCredentials(true)

Do not reflect any origin back to make the error go away. That grants every website the ability to call your API with the user's cookies. Keep the list of allowed origins in configuration, per environment, so staging can allow its own front end without opening production.

Prefer the proxy for same-site deployments

If the front end and the API are served from the same site, CORS is not needed at all. Serving both behind one reverse proxy under one origin, with /api routed to the application, removes the preflight round trip and the whole category of error. Many teams adopt CORS because the development server and the API run on different ports, and then carry the configuration into production. A development proxy in the front end tool, forwarding /api to the backend, gives the same-origin behaviour in development too.

Debug the browser's side as well

The server configuration is half of a CORS problem and the browser is the other. Open the network panel and find the failing request. A preflight appears as an OPTIONS entry just before the real one, and its response headers tell you what the server allowed. Compare them with what the request asks for: Access-Control-Request-Method and Access-Control-Request-Headers list what the page wants, and the response must allow each of them. A custom header such as X-Request-Id or Authorization forces a preflight and must appear in Access-Control-Allow-Headers, so a front end that adds a header in a new release can start failing with no server change. List the headers your front end sends and put them in allowedHeaders explicitly, or use * for headers when credentials are not involved.

Where this does not apply

If the same-origin policy is not involved, such as a server calling your API, there is no CORS and the error is something else. In production, terminating CORS at a reverse proxy or API gateway is common and avoids duplicate headers; do not set it in both places, because a doubled Access-Control-Allow-Origin header is itself rejected by browsers. See the Spring CORS reference, and for the security side Spring Security 403 on POST. Related status errors that look similar from the browser are 405 Method Not Allowed and 415 Unsupported Media Type. The Spring MVC reference documents the behavior in detail.

Also inSecurity
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.