Spring Boot CORS: letting browser front ends call your API

CORS decides whether JavaScript on another origin may read your API's responses, and most CORS bugs are preflight requests answered by the wrong component. This page explains how browsers apply CORS, then runs @CrossOrigin, a global configuration, the credentials rule, Spring Security's cors() switch and a CorsFilter in front of your own filters.

Contents

What CORS is and why browsers need it

Browsers follow the same-origin policy: JavaScript loaded from one origin may not read responses from another origin. An origin is the combination of scheme, host and port, so https://shop.example.com, http://shop.example.com and https://api.example.com are three different origins. Without this rule, any web page you visit could call your bank's API with your cookies and read the answer.

Cross-Origin Resource Sharing (CORS) is the standard way for a server to relax that rule for chosen origins. The browser sends an Origin header with each cross-origin request, and lets the page read the response only if the server answers with a matching Access-Control-Allow-Origin header. Requests come in two kinds:

  • Simple requests: GET, HEAD or POST with only basic headers and a form or plain-text content type. The browser sends them directly and checks the response headers afterwards.
  • Preflighted requests: anything else, such as PUT, DELETE, a JSON body or an Authorization header. The browser first sends an OPTIONS request with Access-Control-Request-Method and Access-Control-Request-Headers, and sends the real request only if the server's answer allows it.

Two facts follow that explain most confusion. First, CORS is enforced by the browser, not by the server. curl, Postman, mobile apps and server-to-server calls ignore it, so CORS never protects an API from those clients; authentication does. Second, a CORS error in the browser console usually means a response lacked the headers, often because something other than the CORS code answered the preflight.

CORS response headers
HeaderSent onMeaning
Access-Control-Allow-OriginPreflight and actualThe origin allowed to read the response
Access-Control-Allow-MethodsPreflightMethods allowed for the actual request
Access-Control-Allow-HeadersPreflightRequest headers the page may send
Access-Control-Allow-CredentialsPreflight and actualWhether cookies and HTTP authentication may be sent
Access-Control-Expose-HeadersActualResponse headers that JavaScript may read
Access-Control-Max-AgePreflightSeconds the browser may cache the preflight answer

Spring offers CORS at three levels: @CrossOrigin on controllers, a global configuration in WebMvcConfigurer, and a CorsFilter that runs before everything else. Spring Security adds its own switch on top. The programs use Spring Boot 4.1 with Spring Framework 7.0 and play the browser's part with the JDK's HttpClient, sending the Origin and preflight headers by hand.

@CrossOrigin on a controller method

The quickest way to open one endpoint to one front end is @CrossOrigin. The program has a closed endpoint and an open one, and sends simple requests from the allowed origin and from another one, then two preflights:

Java
package demo.basics;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class CrossOriginBasics {

    @RestController
    static class Endpoints {
        @GetMapping("/closed/stock")
        public String closed() {
            return "42 in stock";
        }

        @CrossOrigin(origins = "https://shop.example.com")
        @GetMapping("/open/stock")
        public String open() {
            return "42 in stock";
        }

        @CrossOrigin(origins = "https://shop.example.com")
        @DeleteMapping("/open/stock")
        public String clear() {
            return "cleared";
        }
    }

    static HttpClient http = HttpClient.newHttpClient();
    static String base;

    static void send(String method, String path, String origin, String requestMethod)
            throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path))
                .method(method, BodyPublishers.noBody())
                .header("Origin", origin);
        if (requestMethod != null) {
            request.header("Access-Control-Request-Method", requestMethod);
        }
        HttpResponse<String> r = http.send(request.build(), BodyHandlers.ofString());
        System.out.println(method + " " + path + "  Origin: " + origin
                + (requestMethod == null ? "" : "  Access-Control-Request-Method: "
                + requestMethod));
        System.out.println("  -> " + r.statusCode() + " " + r.body());
        r.headers().map().forEach((name, values) -> {
            if (name.startsWith("access-control") || name.equals("vary")) {
                System.out.println("     " + name + ": " + String.join(", ", values));
            }
        });
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(CrossOriginBasics.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            base = "http://localhost:" + port;

            System.out.println("--- simple requests ---");
            send("GET", "/closed/stock", "https://shop.example.com", null);
            send("GET", "/open/stock", "https://shop.example.com", null);
            send("GET", "/open/stock", "https://evil.example.net", null);
            System.out.println("--- preflight requests ---");
            send("OPTIONS", "/open/stock", "https://shop.example.com", "DELETE");
            send("OPTIONS", "/closed/stock", "https://shop.example.com", "GET");
        }
    }
}
Output
--- simple requests ---
GET /closed/stock  Origin: https://shop.example.com
  -> 200 42 in stock
GET /open/stock  Origin: https://shop.example.com
  -> 200 42 in stock
     access-control-allow-origin: https://shop.example.com
     vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
GET /open/stock  Origin: https://evil.example.net
  -> 403 Invalid CORS request
     vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
--- preflight requests ---
OPTIONS /open/stock  Origin: https://shop.example.com  Access-Control-Request-Method: DELETE
  -> 200 
     access-control-allow-methods: DELETE
     access-control-allow-origin: https://shop.example.com
     access-control-max-age: 1800
     vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
OPTIONS /closed/stock  Origin: https://shop.example.com  Access-Control-Request-Method: GET
  -> 200
  • The closed endpoint answered 200 with the data, but with no Access-Control-Allow-Origin. The request reached the server and ran; only the browser would refuse to show the result to the page. This is why CORS is no protection against requests with side effects.
  • The open endpoint returned access-control-allow-origin: https://shop.example.com, the exact origin, which lets a browser page on the shop read the response.
  • From https://evil.example.net, Spring answered 403 Invalid CORS request and did not run the controller. Spring goes further than the standard here: it rejects requests from origins that are not allowed instead of only leaving out the header.
  • The preflight for DELETE got 200 with access-control-allow-methods: DELETE and access-control-max-age: 1800. With @CrossOrigin, the allowed methods default to the methods of the mapping, and the cache time to 30 minutes.
  • The preflight to the closed endpoint got 200 but no CORS headers at all. A browser treats that as a refusal and never sends the real request.
  • Every CORS response carried Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers, which stops caches from serving one origin's answer to another.

@CrossOrigin can also go on the controller class, where it applies to every method. Without origins, it allows all origins, which is rarely what you want outside development.

Global configuration with WebMvcConfigurer

Annotations scattered over controllers are hard to review, and the allowed origins usually differ between environments. A single addCorsMappings keeps the rules in one place. The program configures an API for all subdomains of example.com with cookies allowed, and adds a broken mapping that many applications contain:

Java
package demo.global;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootApplication
public class GlobalCors implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOriginPatterns("https://*.example.com")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("Authorization", "Content-Type")
                .exposedHeaders("X-Total-Count")
                .allowCredentials(true)
                .maxAge(3600);
        registry.addMapping("/legacy/**")
                .allowedOrigins("*")
                .allowCredentials(true);          // not allowed together with "*"
    }

    @RestController
    static class Endpoints {
        @GetMapping("/api/orders")
        public ResponseEntity<String> orders() {
            return ResponseEntity.ok().header("X-Total-Count", "2").body("[1,2]");
        }

        @PostMapping("/api/orders")
        public String create() {
            return "created";
        }

        @GetMapping("/legacy/orders")
        public String legacy() {
            return "[1,2]";
        }
    }

    static HttpClient http = HttpClient.newHttpClient();
    static String base;

    static void send(String method, String path, String... headers) throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path))
                .method(method, BodyPublishers.noBody());
        StringBuilder sent = new StringBuilder();
        for (int i = 0; i < headers.length; i += 2) {
            request.header(headers[i], headers[i + 1]);
            sent.append("\n     > ").append(headers[i]).append(": ").append(headers[i + 1]);
        }
        HttpResponse<String> r = http.send(request.build(), BodyHandlers.ofString());
        System.out.println(method + " " + path + sent);
        String body = r.statusCode() == 500 ? "(error page)" : r.body();
        System.out.println("  -> " + r.statusCode() + " " + body);
        r.headers().map().forEach((name, values) -> {
            if (name.startsWith("access-control")) {
                System.out.println("     " + name + ": " + String.join(", ", values));
            }
        });
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(GlobalCors.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=OFF")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            base = "http://localhost:" + port;

            send("OPTIONS", "/api/orders", "Origin", "https://admin.example.com",
                 "Access-Control-Request-Method", "POST",
                 "Access-Control-Request-Headers", "authorization,content-type");
            send("OPTIONS", "/api/orders", "Origin", "https://admin.example.com",
                 "Access-Control-Request-Method", "POST",
                 "Access-Control-Request-Headers", "x-debug");
            send("OPTIONS", "/api/orders", "Origin", "https://admin.example.com",
                 "Access-Control-Request-Method", "PATCH");
            send("GET", "/api/orders", "Origin", "https://admin.example.com");
            send("GET", "/api/orders", "Origin", "https://example.com");
            send("GET", "/legacy/orders", "Origin", "https://admin.example.com");

            // The exception behind that 500, reproduced outside the server
            CorsConfiguration legacy = new CorsConfiguration();
            legacy.addAllowedOrigin("*");
            legacy.setAllowCredentials(true);
            try {
                legacy.validateAllowCredentials();
            } catch (IllegalArgumentException e) {
                System.out.println("IllegalArgumentException: " + e.getMessage());
            }
        }
    }
}
Output
OPTIONS /api/orders
     > Origin: https://admin.example.com
     > Access-Control-Request-Method: POST
     > Access-Control-Request-Headers: authorization,content-type
  -> 200 
     access-control-allow-credentials: true
     access-control-allow-headers: authorization, content-type
     access-control-allow-methods: GET,POST,PUT,DELETE
     access-control-allow-origin: https://admin.example.com
     access-control-expose-headers: X-Total-Count
     access-control-max-age: 3600
OPTIONS /api/orders
     > Origin: https://admin.example.com
     > Access-Control-Request-Method: POST
     > Access-Control-Request-Headers: x-debug
  -> 403 Invalid CORS request
OPTIONS /api/orders
     > Origin: https://admin.example.com
     > Access-Control-Request-Method: PATCH
  -> 403 Invalid CORS request
GET /api/orders
     > Origin: https://admin.example.com
  -> 200 [1,2]
     access-control-allow-credentials: true
     access-control-allow-origin: https://admin.example.com
     access-control-expose-headers: X-Total-Count
GET /api/orders
     > Origin: https://example.com
  -> 403 Invalid CORS request
GET /legacy/orders
     > Origin: https://admin.example.com
  -> 500 (error page)
IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
  • The first preflight asked for POST with authorization and content-type, and all were allowed. The answer listed all four allowed methods and repeated the requested headers. Because allowCredentials(true) is set, the allowed origin is the exact https://admin.example.com, never *.
  • allowedOriginPatterns("https://*.example.com") matched admin.example.com but not https://example.com itself, which got 403 on the simple GET. Add the bare domain as a second pattern if it needs access.
  • A preflight asking for the header x-debug, and one asking for PATCH, both got 403, because neither is in the configuration.
  • The actual GET carried access-control-expose-headers: X-Total-Count. Without it, browser JavaScript can read only a few basic response headers, so a paging header like this one would look empty to the front end.
  • The /legacy/** mapping combines allowedOrigins("*") with allowCredentials(true). The application started normally, but the cross-origin request to that path failed with 500. The last line shows the exception behind it, reproduced outside the server.

The rule behind that exception comes from the CORS standard: a response that allows credentials must name one origin, because * together with cookies would let any site act as the user. allowedOriginPatterns is the fix: with "*" or a wildcard pattern, Spring echoes the request's origin instead of sending *. Use it only with a real pattern; allowedOriginPatterns("*") with credentials is legal but gives every site the user's session.

The defaults of addMapping differ from those of @CrossOrigin: all origins, only GET, HEAD and POST, all headers, and 1800 seconds. When both apply to a method, Spring combines them. Spring Boot has no property for application CORS; only Actuator endpoints have their own management.endpoints.web.cors.* settings.

CORS with Spring Security

With Spring Security on the classpath, every request passes the security filter chain before it reaches Spring MVC. A preflight carries no credentials, because the browser sends them only with the real request. This program runs the same secured API twice, without and with http.cors():

Java
package demo.security;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.Base64;
import java.util.List;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@SpringBootApplication
public class SecurityCors {

    @Bean
    SecurityFilterChain api(HttpSecurity http, Environment env) throws Exception {
        http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
            .httpBasic(Customizer.withDefaults());
        if (env.getProperty("cors-in-security", Boolean.class, false)) {
            http.cors(Customizer.withDefaults());   // uses the CorsConfigurationSource bean
        }
        return http.build();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(List.of("https://shop.example.com"));
        config.setAllowedMethods(List.of("GET", "POST"));
        config.setAllowedHeaders(List.of("Authorization"));
        config.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/api/**", config);
        return source;
    }

    @Bean
    UserDetailsService users() {
        return new InMemoryUserDetailsManager(User.withUsername("ana")
                .password("{noop}pw").roles("USER").build());
    }

    @RestController
    static class Endpoints {
        @CrossOrigin(origins = "https://shop.example.com")   // read by Spring MVC only
        @GetMapping("/api/profile")
        public String profile() {
            return "profile of ana";
        }
    }

    static void send(String base, String method, String... headers) throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + "/api/profile"))
                .method(method, BodyPublishers.noBody())
                .header("Origin", "https://shop.example.com");
        for (int i = 0; i < headers.length; i += 2) {
            request.header(headers[i], headers[i + 1]);
        }
        HttpResponse<String> r = HttpClient.newHttpClient()
                .send(request.build(), BodyHandlers.ofString());
        System.out.println("  " + method + (method.equals("OPTIONS") ? " (preflight)" : "")
                + " -> " + r.statusCode() + ", Access-Control-Allow-Origin: "
                + r.headers().firstValue("Access-Control-Allow-Origin").orElse("(none)"));
    }

    static void run(boolean corsInSecurity) throws Exception {
        System.out.println("http.cors() " + (corsInSecurity ? "enabled" : "not called") + ":");
        try (var context = new SpringApplicationBuilder(SecurityCors.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=OFF", "cors-in-security=" + corsInSecurity)
                .run()) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            String base = "http://localhost:" + port;
            String basic = "Basic " + Base64.getEncoder().encodeToString("ana:pw".getBytes());
            send(base, "OPTIONS", "Access-Control-Request-Method", "GET",
                 "Access-Control-Request-Headers", "authorization");
            send(base, "GET", "Authorization", basic);
        }
    }

    public static void main(String[] args) throws Exception {
        run(false);
        run(true);
    }
}
Output
http.cors() not called:
  OPTIONS (preflight) -> 401, Access-Control-Allow-Origin: (none)
  GET -> 200, Access-Control-Allow-Origin: https://shop.example.com
http.cors() enabled:
  OPTIONS (preflight) -> 200, Access-Control-Allow-Origin: https://shop.example.com
  GET -> 200, Access-Control-Allow-Origin: https://shop.example.com
  • Without http.cors(), the preflight got 401 from Spring Security, with no CORS headers. Spring MVC and its @CrossOrigin never saw it. A browser would report a CORS error and never send the real request.
  • The real GET with the Authorization header worked in both runs, which is why this problem does not show up in tests with curl or Postman. Only browsers send preflights.
  • With http.cors(Customizer.withDefaults()), Spring Security added a CorsFilter near the start of its chain, using the CorsConfigurationSource bean. The preflight got 200 with the allowed origin before authentication was checked.

When there is no CorsConfigurationSource bean, Spring Security's cors() uses Spring MVC's configuration instead, including @CrossOrigin and addCorsMappings. A separate run of this program without the bean confirmed it: the preflight got 200 from @CrossOrigin alone. Defining the bean, as here, makes the security chain the single source of truth. This program added spring-boot-starter-security to the classpath; the other programs on this page ran with Spring Security's auto-configuration excluded, since they have no use for it.

CorsFilter in front of your own filters

The same problem appears without Spring Security whenever a filter of your own rejects requests that lack credentials. Here an API key filter answers 401 for any request without X-Api-Key. The program runs once with @CrossOrigin only, and once with Spring's CorsFilter registered before every other filter:

Java
package demo.corsfilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.List;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.filter.OncePerRequestFilter;

@SpringBootApplication
public class CorsFilterFirst {

    // An authentication filter written by hand: every request needs an API key
    @Bean
    FilterRegistrationBean<OncePerRequestFilter> apiKeyFilter() {
        OncePerRequestFilter filter = new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request,
                                            HttpServletResponse response, FilterChain chain)
                    throws ServletException, IOException {
                if (request.getHeader("X-Api-Key") == null) {
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    return;
                }
                chain.doFilter(request, response);
            }
        };
        FilterRegistrationBean<OncePerRequestFilter> registration =
                new FilterRegistrationBean<>(filter);
        registration.setOrder(0);
        return registration;
    }

    // Answers CORS before any other filter, including the API key check
    @Bean
    @ConditionalOnProperty(name = "cors-filter", havingValue = "true")
    FilterRegistrationBean<CorsFilter> corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(List.of("https://shop.example.com"));
        config.setAllowedMethods(List.of("GET"));
        config.setAllowedHeaders(List.of("X-Api-Key"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean<CorsFilter> registration =
                new FilterRegistrationBean<>(new CorsFilter(source));
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return registration;
    }

    @RestController
    static class Endpoints {
        @CrossOrigin(origins = "https://shop.example.com", allowedHeaders = "X-Api-Key")
        @GetMapping("/api/basket")
        public String basket() {
            return "2 items";
        }
    }

    static void send(String base, String method, String... headers) throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + "/api/basket"))
                .method(method, BodyPublishers.noBody())
                .header("Origin", "https://shop.example.com");
        for (int i = 0; i < headers.length; i += 2) {
            request.header(headers[i], headers[i + 1]);
        }
        HttpResponse<String> r = HttpClient.newHttpClient()
                .send(request.build(), BodyHandlers.ofString());
        System.out.println("  " + method + (method.equals("OPTIONS") ? " (preflight)" : "")
                + " -> " + r.statusCode() + ", Access-Control-Allow-Origin: "
                + r.headers().firstValue("Access-Control-Allow-Origin").orElse("(none)"));
    }

    static void run(boolean corsFilter) throws Exception {
        System.out.println(corsFilter ? "CorsFilter first in the chain:"
                                      : "@CrossOrigin only (Spring MVC):");
        try (var context = new SpringApplicationBuilder(CorsFilterFirst.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=OFF", "cors-filter=" + corsFilter)
                .run()) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            String base = "http://localhost:" + port;
            send(base, "OPTIONS", "Access-Control-Request-Method", "GET",
                 "Access-Control-Request-Headers", "x-api-key");
            send(base, "GET", "X-Api-Key", "k-123");
        }
    }

    public static void main(String[] args) throws Exception {
        run(false);
        run(true);
    }
}
Output
@CrossOrigin only (Spring MVC):
  OPTIONS (preflight) -> 401, Access-Control-Allow-Origin: (none)
  GET -> 200, Access-Control-Allow-Origin: https://shop.example.com
CorsFilter first in the chain:
  OPTIONS (preflight) -> 200, Access-Control-Allow-Origin: https://shop.example.com
  GET -> 200, Access-Control-Allow-Origin: https://shop.example.com
  • With @CrossOrigin only, the preflight hit the API key filter first and got 401. The annotation is read by Spring MVC, which comes after all filters.
  • With the CorsFilter at Ordered.HIGHEST_PRECEDENCE, the preflight was answered with 200 and the CORS headers. CorsFilter ends the chain itself for a valid preflight, so the API key filter never saw it.
  • The real GET, which carries the key, passed both filters in both runs.

The same rule applies to handler interceptors: Spring MVC runs them for preflight requests too, with a PreFlightHttpRequestHandler as the handler. In a separate test, an interceptor that answered 401 turned an allowed preflight into a 401. Skip preflights in such code with CorsUtils.isPreFlightRequest(request).

Common CORS mistakes

  • Origins with a path or slash: an origin is only scheme, host and port. https://shop.example.com/ with a trailing slash never matches the browser's Origin header.
  • Testing without a browser: CORS problems appear only in browsers. Test preflights explicitly, as these programs do, or in the browser's network tab.
  • Reading custom response headers: headers such as X-Total-Count or Location are invisible to JavaScript until they are listed in exposedHeaders.
  • CORS as access control: allowing only your own front end does not stop other clients from calling the API. Authentication and CSRF protection do that.
  • Proxies and gateways: when a gateway in front of the application also adds CORS headers, responses can end up with two Access-Control-Allow-Origin values, which browsers reject. Configure CORS in one layer.
  • Development servers: a front-end dev server on http://localhost:5173 is a different origin from the API on http://localhost:8080. Allow it only in a development profile, or use the dev server's proxy so that no CORS is needed.

Choosing where to configure CORS

CORS options in Spring Boot
SituationUse
One or two endpoints for one front end@CrossOrigin(origins = ...)
A whole API with one policyaddCorsMappings in a WebMvcConfigurer
Spring Security in the applicationhttp.cors() with a CorsConfigurationSource bean
Your own authentication filters or interceptorsCorsFilter at the highest precedence, or skip preflights
Cookies or HTTP authentication across originsallowCredentials(true) with explicit origins or allowedOriginPatterns
Many subdomainsallowedOriginPatterns("https://*.example.com")
Front end needs a response headerexposedHeaders
Fewer preflight round tripsmaxAge; browsers may cap it at a lower value

Whatever you choose, configure CORS in one place and make sure it answers preflights before any authentication does. For the filter chain these settings live in, see Spring Boot filters.