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
submits a hidden form toevil.example.net . 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.bank.example.com/transfer - 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 | CORS | |
|---|---|---|
| Protects | Your users, from actions done in their name | Nothing; it grants access that the browser would otherwise block |
| Matters when | The browser authenticates automatically: session cookies, Basic auth remembered by the browser | A page served from another origin calls your API with JavaScript |
| Mechanism | A token sent in a header or form field, compared with one stored on the server or in a cookie | Access-Control-Allow-*OPTIONS |
| Enforced by | The server (Spring's CsrfFilter | The browser |
| Spring Security default | On, for every method except GET, HEAD, TRACE and OPTIONS | Off until you call http.cors(...) |
| Typical failure | 403 on POST, PUT or DELETE | The 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.comhttps://api.example.comexample.comSameSitejava.net.http.HttpClient
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:
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])));
}
}
}
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
needed no token, because GET must not change anything and is never checked.GET /balance got 403 although the request had valid Basic credentials.POST /transfer runs before the authentication filters, so being logged in does not help.CsrfFilter returned the header nameGET /csrf and a 96-character token. A controller can take aX-CSRF-TOKEN parameter for this; a server-rendered page gets it as the request attributeCsrfToken , and Thymeleaf adds a hidden field to forms by itself._csrf- 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()/error
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()
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);
}
}
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
, the first GET set noCookieCsrfTokenRepository.withHttpOnlyFalse() cookie. Since Spring Security 6.0, the token is loaded lazily, only when something reads it, and a normal endpoint does not.XSRF-TOKEN , which takes aGET /api/csrf parameter, did trigger it, and the 36-character cookie appeared.CsrfToken- The POST with that cookie value in
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.X-XSRF-TOKEN - With
, the first GET already set the cookie, and the POST with the raw cookie value succeeded.csrf.spa()
spa()HttpOnlyCsrfTokenRequestHandler
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
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() : "");
}
}
}
}
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
is served by the first chain, which has/api/orders and no sessions, so the POST succeeded.csrf.disable() is in the second chain but listed in/webhooks/payment , so it skipped the check. A payment provider calling a webhook has no token to send; verify its signature instead.ignoringRequestMatchers is still protected, and got 403./account/email
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
so that no session cookie is ever created.SessionCreationPolicy.STATELESS - 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 AuthorizationOPTIONShttps://app.example.com
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"));
}
}
}
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
, the requested headerGET,POST , and a max age of 3600 seconds, which lets the browser cache this answer for an hour instead of repeating the preflight.authorization got 403https://evil.example.net with no CORS headers, so a browser would block the real request.Invalid CORS request- A
from the allowed origin was refused the same way, because only GET and POST are listed.DELETE - The real GET without credentials got 401, but its response still carried
. That matters: without it the browser would hide the 401 from the script, which would see only a generic network error.Access-Control-Allow-Origin
The preflight succeeded without credentials although every request needs a login. Browsers never send credentials on a preflight, so http.cors(...)CorsFilterCustomizer.withDefaults()corsConfigurationSource
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 @CrossOriginCorsRegistryhttp.cors()
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));
}
}
}
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
, 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.WithoutCors - In
, the single lineWithCors fixed both. The security chain now uses the MVC settings: the.cors(Customizer.withDefaults()) origin for@CrossOrigin , and the pattern from/api/annotated forCorsRegistry , with/api/registry .allow-credentials: true withallowedOrigins("*") threwallowCredentials(true) . Browsers refuse credentialed responses withIllegalArgumentException , so Spring refuses the combination.Access-Control-Allow-Origin: * is the fix: it matchedallowedOriginPatterns("https://*.example.com") and echoed that exact origin back, and returned null forhttps://shop.example.com .https://example.org
The wildcard trap is worse in a running application than in this direct check. When the same mapping was registered through CorsRegistryhttps://*
Choosing CSRF and CORS settings
| Application | CSRF | CORS |
|---|---|---|
| Server-rendered site, same origin | Default: tokens in the session, hidden form fields | Not needed |
| Single-page app on the same origin, session cookie | csrf.spa() | Not needed |
| Single-page app on another origin, session cookie | csrf.spa() | http.cors()allowCredentials(true) |
| API with bearer tokens in a header | Disabled, sessions STATELESS | http.cors() |
| JWT stored in a cookie | Keep it on | As for session cookies |
| Webhooks from other services | ignoringRequestMatchers | Not needed; servers do not use CORS |
| Mobile or server-to-server clients only | Disabled | Not needed |
When a browser request fails, look at the status first: a 403 on a POST is usually CSRF, a 401 on an OPTIONShttp.cors()