CSRF and CORS in Spring Security: two browser problems, two different fixes

CSRF and CORS are often configured together and often confused. CSRF protection stops another site from using a logged-in user's cookies to send requests to your application; CORS lets a page from another origin read your responses. This page explains what each one guards against, then runs both in a Spring Boot 4.1 application, including the token and preflight mistakes that cause 403 and 401 errors.

Contents

Two browser problems that are easy to mix up

Both CSRF and CORS exist because browsers attach cookies automatically and run pages from many sites side by side. They solve opposite problems:

  • Cross-site request forgery (CSRF): a page on evil.example.net submits a hidden form to bank.example.com/transfer. The browser sends the bank's session cookie with it, so the bank sees a logged-in user. CSRF protection makes the server reject state-changing requests that do not carry a secret the attacker's page cannot know.
  • Cross-origin resource sharing (CORS): by default, the browser lets JavaScript on one origin send requests to another but not read the responses (the same-origin policy). CORS is the server saying which other origins may read its responses. It relaxes a browser rule; it does not protect the server.
CSRF protection and CORS compared
CSRF protectionCORS
ProtectsYour users, from actions done in their nameNothing; it grants access that the browser would otherwise block
Matters whenThe browser authenticates automatically: session cookies, Basic auth remembered by the browserA page served from another origin calls your API with JavaScript
MechanismA token sent in a header or form field, compared with one stored on the server or in a cookieAccess-Control-Allow-* response headers, often after an OPTIONS preflight
Enforced byThe server (Spring's CsrfFilter)The browser
Spring Security defaultOn, for every method except GET, HEAD, TRACE and OPTIONSOff until you call http.cors(...)
Typical failure403 on POST, PUT or DELETEThe browser console reports a CORS error, while the server log may show nothing at all

An origin is the scheme, host and port together, so https://app.example.com and https://api.example.com are different origins. A "site" is broader: both are on the same site, example.com. That difference matters for the SameSite cookie attribute, which stops cookies from being sent on most cross-site requests and so reduces CSRF risk. It does not replace tokens, because a sibling subdomain counts as the same site and can still forge requests. The examples are Spring Boot 4.1 applications on Spring Security 7.1 that call themselves with java.net.http.HttpClient, which plays the browser: it sends the cookies and headers a browser would send.

CSRF tokens in a session-based application

With the default configuration, the server stores a CSRF token in the user's HTTP session and expects a copy of it on every state-changing request. This program plays both the user's browser and an attacker, who has no access to the user's session and so cannot read the token:

Java
package demo.csrf.basics;

import java.net.CookieManager;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

public class CsrfBasics {

    @RestController
    static class TransferController {
        @GetMapping("/csrf")
        String token(CsrfToken token) {
            return token.getHeaderName() + "=" + token.getToken();
        }

        @GetMapping("/balance")
        String balance() {
            return "balance 100";
        }

        @PostMapping("/transfer")
        String transfer() {
            return "transferred 50";
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import(TransferController.class)
    static class App {
        @Bean
        SecurityFilterChain security(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests(auth -> auth
                            .requestMatchers("/error").permitAll()
                            .anyRequest().authenticated())
                    .httpBasic(Customizer.withDefaults());       // CSRF is on by default
            return http.build();
        }
    }

    static final String BASIC = "Basic "
            + Base64.getEncoder().encodeToString("ann:pw".getBytes());

    static String send(HttpClient client, HttpRequest.Builder request) throws Exception {
        HttpResponse<String> r = client.send(request.header("Authorization", BASIC).build(),
                HttpResponse.BodyHandlers.ofString());
        return r.statusCode() + (r.statusCode() == 200 ? " " + r.body() : "");
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(App.class);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "spring.security.user.name", "ann", "spring.security.user.password", "pw"));
        try (ConfigurableApplicationContext context = app.run()) {
            String base = "http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port");
            HttpClient browser = HttpClient.newBuilder()
                    .cookieHandler(new CookieManager()).build();
            HttpClient attacker = HttpClient.newBuilder()
                    .cookieHandler(new CookieManager()).build();
            HttpRequest.Builder post = HttpRequest.newBuilder(URI.create(base + "/transfer"))
                    .POST(HttpRequest.BodyPublishers.noBody());

            System.out.println("GET  /balance, no token        -> "
                    + send(browser, HttpRequest.newBuilder(URI.create(base + "/balance"))));
            System.out.println("POST /transfer, no token       -> " + send(browser, post.copy()));

            String[] token = send(browser, HttpRequest.newBuilder(URI.create(base + "/csrf")))
                    .substring(4).split("=", 2);
            System.out.println("GET  /csrf gives header " + token[0] + " and a token of "
                    + token[1].length() + " chars");
            System.out.println("POST /transfer, with the token -> "
                    + send(browser, post.copy().header(token[0], token[1])));
            System.out.println("Same token from another session -> "
                    + send(attacker, post.copy().header(token[0], token[1])));
        }
    }
}
Output
GET  /balance, no token        -> 200 balance 100
POST /transfer, no token       -> 403
GET  /csrf gives header X-CSRF-TOKEN and a token of 96 chars
POST /transfer, with the token -> 200 transferred 50
Same token from another session -> 403
  • GET /balance needed no token, because GET must not change anything and is never checked.
  • POST /transfer got 403 although the request had valid Basic credentials. CsrfFilter runs before the authentication filters, so being logged in does not help.
  • GET /csrf returned the header name X-CSRF-TOKEN and a 96-character token. A controller can take a CsrfToken parameter for this; a server-rendered page gets it as the request attribute _csrf, and Thymeleaf adds a hidden field to forms by itself.
  • With the token in the header, the same POST succeeded: transferred 50.
  • The same token sent from a different client, with no access to the user's session, got 403. The server compares the token with the one in the caller's own session, so a token copied from somewhere else is useless.

The token is 96 characters because Spring Security 6 and later masks it: each response gives a different random encoding of the same secret, which defends against the BREACH compression attack. A client therefore cannot compare tokens from two responses, but each one works.

The chain also contains requestMatchers("/error").permitAll(). Without it, this program printed 401 instead of 403 for the rejected POSTs: the CSRF filter sent a 403 error, Spring Boot forwarded it to /error, and that forward was refused because the user had not been authenticated yet. A 401 that should be a 403 is a common source of confusion when debugging CSRF.

CSRF for single-page applications: csrf.spa()

A JavaScript application cannot read a server-side session, so the token usually travels in a cookie that JavaScript reads and copies into a header, the convention used by Angular and many HTTP clients. This program compares a configuration that only switches to a cookie with one that uses csrf.spa(), and sends the cookie value back as a script would:

Java
package demo.csrf.spa;

import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

public class CsrfSpa {

    @RestController
    static class Api {
        @GetMapping("/api/profile")
        String profile() {
            return "profile";
        }

        @GetMapping("/api/csrf")
        String csrf(CsrfToken token) {
            return "token value sent in the body: " + token.getToken().length() + " chars";
        }

        @PostMapping("/api/profile")
        String update() {
            return "updated";
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import(Api.class)
    static class CookieOnly {
        @Bean
        SecurityFilterChain security(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
                    .csrf(csrf -> csrf.csrfTokenRepository(
                            CookieCsrfTokenRepository.withHttpOnlyFalse()));
            return http.build();
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import(Api.class)
    static class Spa {
        @Bean
        SecurityFilterChain security(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
                    .csrf(csrf -> csrf.spa());
            return http.build();
        }
    }

    static String cookie(CookieManager cookies) {
        return cookies.getCookieStore().getCookies().stream()
                .filter(c -> c.getName().equals("XSRF-TOKEN"))
                .map(HttpCookie::getValue).findFirst().orElse(null);
    }

    static void run(Class<?> config) throws Exception {
        SpringApplication app = new SpringApplication(config);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "WARN", "spring.security.user.password", "pw"));
        try (ConfigurableApplicationContext context = app.run()) {
            String base = "http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port");
            CookieManager cookies = new CookieManager();
            HttpClient client = HttpClient.newBuilder().cookieHandler(cookies).build();
            System.out.println(config.getSimpleName() + ":");

            String token = null;
            for (String path : new String[] {"/api/profile", "/api/csrf"}) {
                HttpResponse<String> get = client.send(
                        HttpRequest.newBuilder(URI.create(base + path)).build(),
                        HttpResponse.BodyHandlers.ofString());
                token = cookie(cookies);
                System.out.println("  GET " + path + " -> " + get.statusCode()
                        + ", XSRF-TOKEN cookie: "
                        + (token == null ? "none" : token.length() + " chars"));
                if (token != null) {
                    break;
                }
            }
            HttpRequest.Builder post = HttpRequest.newBuilder(URI.create(base + "/api/profile"))
                    .POST(HttpRequest.BodyPublishers.noBody());
            if (token != null) {
                post.header("X-XSRF-TOKEN", token);
            }
            HttpResponse<String> r = client.send(post.build(),
                    HttpResponse.BodyHandlers.ofString());
            System.out.println("  POST with X-XSRF-TOKEN = cookie value -> " + r.statusCode());
        }
    }

    public static void main(String[] args) throws Exception {
        run(CookieOnly.class);
        run(Spa.class);
    }
}
Output
CookieOnly:
  GET /api/profile -> 200, XSRF-TOKEN cookie: none
  GET /api/csrf -> 200, XSRF-TOKEN cookie: 36 chars
  POST with X-XSRF-TOKEN = cookie value -> 403
Spa:
  GET /api/profile -> 200, XSRF-TOKEN cookie: 36 chars
  POST with X-XSRF-TOKEN = cookie value -> 200
  • With only CookieCsrfTokenRepository.withHttpOnlyFalse(), the first GET set no XSRF-TOKEN cookie. Since Spring Security 6.0, the token is loaded lazily, only when something reads it, and a normal endpoint does not.
  • GET /api/csrf, which takes a CsrfToken parameter, did trigger it, and the 36-character cookie appeared.
  • The POST with that cookie value in X-XSRF-TOKEN still got 403. The cookie holds the raw token, but the default request handler expects the masked form from the previous section. Two separate changes are needed, and this configuration made only one.
  • With csrf.spa(), the first GET already set the cookie, and the POST with the raw cookie value succeeded.

spa() in Spring Security 7 sets up all three parts: the cookie repository with HttpOnly off so that JavaScript can read it, a handler that accepts the raw token in a header and the masked one in a form field, and loading of the token on every request so the cookie always exists. On Spring Security 6.x, the reference documentation shows the same setup written by hand, with a custom CsrfTokenRequestHandler and a filter that reads the token.

When CSRF protection can be turned off

CSRF works only when the browser adds credentials by itself. An API whose clients send a bearer token in the Authorization header gives an attacker's page nothing to borrow, so CSRF protection there only gets in the way. This program has a stateless API chain, a webhook endpoint and a session-style endpoint, and posts to all three without a token:

Java
package demo.csrf.scope;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

public class CsrfScope {

    @RestController
    static class Endpoints {
        @PostMapping("/api/orders")
        String order() {
            return "order created";
        }

        @PostMapping("/webhooks/payment")
        String webhook() {
            return "webhook accepted";
        }

        @PostMapping("/account/email")
        String email() {
            return "email changed";
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import(Endpoints.class)
    static class App {
        @Bean
        @Order(1)
        SecurityFilterChain api(HttpSecurity http) throws Exception {
            http.securityMatcher("/api/**")
                    .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
                    .httpBasic(Customizer.withDefaults())
                    .sessionManagement(s -> s.sessionCreationPolicy(
                            SessionCreationPolicy.STATELESS))
                    .csrf(csrf -> csrf.disable());
            return http.build();
        }

        @Bean
        @Order(2)
        SecurityFilterChain web(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests(auth -> auth
                            .requestMatchers("/webhooks/**", "/error").permitAll()
                            .anyRequest().authenticated())
                    .httpBasic(Customizer.withDefaults())
                    .csrf(csrf -> csrf.ignoringRequestMatchers("/webhooks/**"));
            return http.build();
        }
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(App.class);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "spring.security.user.name", "ann", "spring.security.user.password", "pw"));
        try (ConfigurableApplicationContext context = app.run()) {
            String base = "http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port");
            String basic = "Basic " + Base64.getEncoder().encodeToString("ann:pw".getBytes());
            for (String path : new String[] {"/api/orders", "/webhooks/payment",
                    "/account/email"}) {
                HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path))
                        .POST(HttpRequest.BodyPublishers.noBody());
                if (!path.startsWith("/webhooks")) {
                    request.header("Authorization", basic);
                }
                HttpResponse<String> r = HttpClient.newHttpClient()
                        .send(request.build(), HttpResponse.BodyHandlers.ofString());
                System.out.printf("POST %-18s no CSRF token -> %d %s%n", path, r.statusCode(),
                        r.statusCode() == 200 ? r.body() : "");
            }
        }
    }
}
Output
POST /api/orders        no CSRF token -> 200 order created
POST /webhooks/payment  no CSRF token -> 200 webhook accepted
POST /account/email     no CSRF token -> 403
  • /api/orders is served by the first chain, which has csrf.disable() and no sessions, so the POST succeeded.
  • /webhooks/payment is in the second chain but listed in ignoringRequestMatchers, so it skipped the check. A payment provider calling a webhook has no token to send; verify its signature instead.
  • /account/email is still protected, and got 403.

Disable CSRF only for requests that cannot be authenticated by the browser alone. The rule of thumb:

  • Safe to disable: APIs that use bearer tokens or API keys in a header, with SessionCreationPolicy.STATELESS so that no session cookie is ever created.
  • Keep it on: anything that uses a session cookie, form login, or a JWT stored in a cookie. A token in a cookie is sent by the browser automatically, exactly like a session id.
  • HTTP Basic from browsers: browsers remember Basic credentials and resend them, so a browser-facing endpoint with Basic auth needs CSRF protection too.

CORS preflight requests

For any request that is not a simple GET or form POST, for example one with an Authorization header or a JSON body, the browser first sends an OPTIONS preflight asking whether the real request is allowed. This program sends three preflights to an API that allows only https://app.example.com, then the real request:

Java
package demo.cors.preflight;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
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;

public class CorsPreflight {

    @RestController
    static class Api {
        @GetMapping("/api/orders")
        String orders() {
            return "orders";
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import(Api.class)
    static class App {
        @Bean
        SecurityFilterChain security(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
                    .httpBasic(Customizer.withDefaults())
                    .cors(Customizer.withDefaults());       // uses the bean below
            return http.build();
        }

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

    static void preflight(String base, String origin, String method) throws Exception {
        HttpRequest request = HttpRequest.newBuilder(URI.create(base + "/api/orders"))
                .method("OPTIONS", HttpRequest.BodyPublishers.noBody())
                .header("Origin", origin)
                .header("Access-Control-Request-Method", method)
                .header("Access-Control-Request-Headers", "authorization")
                .build();
        HttpResponse<String> r = HttpClient.newHttpClient()
                .send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println("OPTIONS from " + origin + ", method " + method + " -> "
                + r.statusCode() + (r.body().isEmpty() ? "" : " " + r.body()));
        r.headers().map().entrySet().stream()
                .filter(e -> e.getKey().startsWith("access-control"))
                .sorted(Map.Entry.comparingByKey())
                .forEach(e -> System.out.println("  " + e.getKey() + ": "
                        + String.join(", ", e.getValue())));
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(App.class);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "WARN", "spring.security.user.password", "pw"));
        try (ConfigurableApplicationContext context = app.run()) {
            String base = "http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port");
            preflight(base, "https://app.example.com", "GET");
            preflight(base, "https://evil.example.net", "GET");
            preflight(base, "https://app.example.com", "DELETE");

            HttpResponse<String> actual = HttpClient.newHttpClient().send(
                    HttpRequest.newBuilder(URI.create(base + "/api/orders"))
                            .header("Origin", "https://app.example.com").build(),
                    HttpResponse.BodyHandlers.ofString());
            System.out.println("GET with Origin, no credentials -> " + actual.statusCode()
                    + ", Access-Control-Allow-Origin: "
                    + actual.headers().firstValue("Access-Control-Allow-Origin").orElse("none"));
        }
    }
}
Output
OPTIONS from https://app.example.com, method GET -> 200
  access-control-allow-headers: authorization
  access-control-allow-methods: GET,POST
  access-control-allow-origin: https://app.example.com
  access-control-max-age: 3600
OPTIONS from https://evil.example.net, method GET -> 403 Invalid CORS request
OPTIONS from https://app.example.com, method DELETE -> 403 Invalid CORS request
GET with Origin, no credentials -> 401, Access-Control-Allow-Origin: https://app.example.com
  • The allowed origin got 200 with four headers: the origin echoed back, the allowed methods GET,POST, the requested header authorization, and a max age of 3600 seconds, which lets the browser cache this answer for an hour instead of repeating the preflight.
  • https://evil.example.net got 403 Invalid CORS request with no CORS headers, so a browser would block the real request.
  • A DELETE from the allowed origin was refused the same way, because only GET and POST are listed.
  • The real GET without credentials got 401, but its response still carried Access-Control-Allow-Origin. That matters: without it the browser would hide the 401 from the script, which would see only a generic network error.

The preflight succeeded without credentials although every request needs a login. Browsers never send credentials on a preflight, so http.cors(...) places Spring's CorsFilter before authentication, and the filter answers preflights itself. Customizer.withDefaults() uses a bean named corsConfigurationSource when there is one, as here, and otherwise the CORS settings of Spring MVC.

CORS traps: the missing cors() and credentials

Most CORS problems in Spring Security applications come from two mistakes: configuring CORS in Spring MVC but not in the security chain, and combining credentials with a wildcard origin. This program runs the same MVC settings, an @CrossOrigin annotation and a CorsRegistry mapping, with and without http.cors(), then checks the wildcard rule directly:

Java
package demo.cors.traps;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

public class CorsTraps {

    @RestController
    static class Api {
        @CrossOrigin(origins = "https://app.example.com")
        @GetMapping("/api/annotated")
        String annotated() {
            return "annotated";
        }

        @GetMapping("/api/registry")
        String registry() {
            return "registry";
        }
    }

    static class MvcCors implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/api/registry")
                    .allowedOriginPatterns("https://*.example.com")
                    .allowCredentials(true);
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import({Api.class, MvcCors.class})
    static class WithoutCors {
        @Bean
        SecurityFilterChain security(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
                    .httpBasic(Customizer.withDefaults());
            return http.build();
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import({Api.class, MvcCors.class})
    static class WithCors {
        @Bean
        SecurityFilterChain security(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
                    .httpBasic(Customizer.withDefaults())
                    .cors(Customizer.withDefaults());
            return http.build();
        }
    }

    static void preflight(String base, String path, String origin) throws Exception {
        HttpResponse<String> r = HttpClient.newHttpClient().send(
                HttpRequest.newBuilder(URI.create(base + path))
                        .method("OPTIONS", HttpRequest.BodyPublishers.noBody())
                        .header("Origin", origin)
                        .header("Access-Control-Request-Method", "GET").build(),
                HttpResponse.BodyHandlers.ofString());
        System.out.println("  OPTIONS " + path + " from " + origin + " -> " + r.statusCode()
                + ", allow-origin: "
                + r.headers().firstValue("Access-Control-Allow-Origin").orElse("none")
                + ", allow-credentials: "
                + r.headers().firstValue("Access-Control-Allow-Credentials").orElse("none"));
    }

    static void run(Class<?> config) throws Exception {
        System.out.println(config.getSimpleName() + ":");
        SpringApplication app = new SpringApplication(config);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "OFF", "spring.security.user.password", "pw"));
        try (ConfigurableApplicationContext context = app.run()) {
            String base = "http://localhost:"
                    + context.getEnvironment().getProperty("local.server.port");
            preflight(base, "/api/annotated", "https://app.example.com");
            preflight(base, "/api/registry", "https://shop.example.com");
        }
    }

    public static void main(String[] args) throws Exception {
        run(WithoutCors.class);
        run(WithCors.class);

        System.out.println("allowedOrigins(\"*\") with allowCredentials(true):");
        CorsConfiguration wildcard = new CorsConfiguration();
        wildcard.addAllowedOrigin("*");
        wildcard.setAllowCredentials(true);
        try {
            wildcard.checkOrigin("https://shop.example.com");
        } catch (IllegalArgumentException e) {
            System.out.println("  " + e.getClass().getSimpleName() + ": "
                    + e.getMessage().substring(0, e.getMessage().indexOf(" since")));
        }
        CorsConfiguration patterns = new CorsConfiguration();
        patterns.addAllowedOriginPattern("https://*.example.com");
        patterns.setAllowCredentials(true);
        System.out.println("allowedOriginPatterns(\"https://*.example.com\"):");
        for (String origin : new String[] {"https://shop.example.com", "https://example.org"}) {
            System.out.println("  " + origin + " -> " + patterns.checkOrigin(origin));
        }
    }
}
Output
WithoutCors:
  OPTIONS /api/annotated from https://app.example.com -> 401, allow-origin: none, allow-credentials: none
  OPTIONS /api/registry from https://shop.example.com -> 401, allow-origin: none, allow-credentials: none
WithCors:
  OPTIONS /api/annotated from https://app.example.com -> 200, allow-origin: https://app.example.com, allow-credentials: none
  OPTIONS /api/registry from https://shop.example.com -> 200, allow-origin: https://shop.example.com, allow-credentials: true
allowedOrigins("*") with allowCredentials(true):
  IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*"
allowedOriginPatterns("https://*.example.com"):
  https://shop.example.com -> https://shop.example.com
  https://example.org -> null
  • In WithoutCors, both preflights got 401 with no CORS headers. The MVC configuration is correct, but the preflight never reached Spring MVC: it carries no credentials, so the security chain rejected it first.
  • In WithCors, the single line .cors(Customizer.withDefaults()) fixed both. The security chain now uses the MVC settings: the @CrossOrigin origin for /api/annotated, and the pattern from CorsRegistry for /api/registry, with allow-credentials: true.
  • allowedOrigins("*") with allowCredentials(true) threw IllegalArgumentException. Browsers refuse credentialed responses with Access-Control-Allow-Origin: *, so Spring refuses the combination.
  • allowedOriginPatterns("https://*.example.com") is the fix: it matched https://shop.example.com and echoed that exact origin back, and returned null for https://example.org.

The wildcard trap is worse in a running application than in this direct check. When the same mapping was registered through CorsRegistry in a test of this application, the preflight returned 200 with no CORS headers and nothing was logged at the default level, so the browser blocked the call with no clue on the server. Prefer a list of exact origins; use patterns only for a family of origins you control, and never a pattern as broad as https://* with credentials, which lets any site read authenticated responses.

Choosing CSRF and CORS settings

Settings for common kinds of application
ApplicationCSRFCORS
Server-rendered site, same originDefault: tokens in the session, hidden form fieldsNot needed
Single-page app on the same origin, session cookiecsrf.spa()Not needed
Single-page app on another origin, session cookiecsrf.spa(), with the cookie's domain shared by both hostshttp.cors(), exact origin, allowCredentials(true)
API with bearer tokens in a headerDisabled, sessions STATELESShttp.cors() for browser clients; no credentials needed
JWT stored in a cookieKeep it onAs for session cookies
Webhooks from other servicesignoringRequestMatchers for that path, plus signature checksNot needed; servers do not use CORS
Mobile or server-to-server clients onlyDisabledNot needed

When a browser request fails, look at the status first: a 403 on a POST is usually CSRF, a 401 on an OPTIONS request means http.cors() is missing, and a CORS error in the console with a 200 preflight means the response headers do not match the request. For the rest of the security chain, see Spring Security in Spring Boot; for bearer-token APIs, see JWT access and refresh tokens and the OAuth2 resource server page.