Integration · Spring Boot

CORS in Spring Boot: setting up CorsConfigurationSource

Spring Boot has no CORS headers turned on anywhere by default, same as every other framework we've covered in this series. What's different is that the fix isn't one line: a plain WebMvcConfigurer bean is enough on its own, but adding spring-boot-starter-security to the classpath, which most real services do, changes which part of the stack is allowed to answer a preflight at all. We built a minimal app on Spring Boot 4.2.0 and Java 21, ran it both ways, and read the exception a common mistake throws before shipping either config.

· ~7 min read

Without Spring Security, one bean is enough

A @RestController with nothing else configured sends no Access-Control-Allow-Origin on any response. The smallest fix is a WebMvcConfigurer bean that registers a mapping through CorsRegistry:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/api/**")
                    .allowedOrigins("https://example.com")
                    .allowedMethods("GET", "POST")
                    .allowedHeaders("Content-Type", "Authorization")
                    .allowCredentials(true);
        }
    };
}

That's the whole thing. With it in place, a preflight from the allowed origin gets back exactly what the browser needs to let the real request through:

$ curl -i -X OPTIONS http://localhost:8080/api/hello \
    -H "Origin: https://example.com" -H "Access-Control-Request-Method: GET"
HTTP/1.1 200
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET,POST
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 1800

The Access-Control-Max-Age: 1800 is worth noticing: we never set a .maxAge(...) call, and Spring filled in 30 minutes on its own. That's shorter than the cap either Chrome or Firefox will actually honor, as covered in CORS preflight caching, but it's not zero, and it's a Spring default rather than anything we asked for. A request from an origin that isn't on the list doesn't get ignored or silently stripped, either; Spring's CORS processing rejects it outright, before the controller runs:

$ curl -i http://localhost:8080/api/hello -H "Origin: https://evil.example"
HTTP/1.1 403
Invalid CORS request

Wildcard origin plus credentials compiles, then fails on the first request

Change .allowedOrigins("https://example.com") to .allowedOrigins("*") while leaving .allowCredentials(true) in place, and nothing in the build complains. The app starts normally too; there's no validation at startup that would catch the combination early. The first request that actually reaches that mapping is where it breaks:

$ curl -i http://localhost:8080/api/hello -H "Origin: https://evil.example"
HTTP/1.1 500
{"timestamp":"...","status":500,"error":"Internal Server Error","path":"/api/hello"}

The server log names the exact rule it's enforcing:

java.lang.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.

This is the same rule the Fetch spec enforces in the browser, covered in CORS with cookies and credentials: a credentialed response can't carry a literal *. Spring just enforces its own copy of that rule server-side, at request time instead of build time, which means it's easy to ship a wildcard-plus-credentials config that looks fine in CI and only throws once production traffic from an origin you didn't list arrives. The fix Spring names in the message is real: swap allowedOrigins for allowedOriginPatterns if you genuinely need to match more than one origin, or list the origins explicitly if you don't.

Spring Security intercepts the preflight before CORS ever runs

Add spring-boot-starter-security to the same project with no other configuration, and every path, including /api/hello, now requires authentication by default. That by itself is expected. What's less obvious is what it does to the preflight:

$ curl -i -X OPTIONS http://localhost:8080/api/hello \
    -H "Origin: https://example.com" -H "Access-Control-Request-Method: GET"
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"

No Access-Control-Allow-Origin, no Access-Control-Allow-Methods, nothing. The WebMvcConfigurer bean from the previous section is still registered and otherwise unchanged, but it never gets a chance to run: Spring Security's filter chain sits in front of Spring MVC's DispatcherServlet, and CorsRegistry's CORS handling is wired into the DispatcherServlet's handler mapping, which is reached only after the servlet filters have let a request through. The default security filter chain demands authentication on the way in, so the OPTIONS request never gets far enough for CorsRegistry to answer it. In a browser this shows up as a CORS error in the console, because the response the browser actually got back has no CORS headers on it at all, but the real cause is that a request never reached the code that would have added them.

Wiring CORS through Security instead of around it

With Spring Security present, the mapping has to move into the SecurityFilterChain itself, as a CorsConfigurationSource bean that http.cors() is told to use:

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowedOrigins(List.of("https://example.com"));
    config.setAllowedMethods(List.of("GET", "POST"));
    config.setAllowedHeaders(List.of("Content-Type", "Authorization"));
    config.setAllowCredentials(true);

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/api/**", config);
    return source;
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .cors(cors -> cors.configurationSource(corsConfigurationSource()))
        .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
        .csrf(csrf -> csrf.disable());
    return http.build();
}

With that in place, the preflight succeeds again, and it succeeds without needing a separate rule to let OPTIONS through: Spring Security's CORS support runs its own filter ahead of the authorization check specifically so a preflight doesn't get rejected for lacking credentials it was never going to send.

$ curl -i -X OPTIONS http://localhost:8080/api/hello \
    -H "Origin: https://example.com" -H "Access-Control-Request-Method: GET"
HTTP/1.1 200
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET,POST
Access-Control-Allow-Credentials: true

The real request is a different story, and this is the part worth watching for: with anyRequest().authenticated(), a GET from the same allowed origin, with no credentials attached, still comes back as a 403, and the CORS headers are present on it:

$ curl -i http://localhost:8080/api/hello -H "Origin: https://example.com"
HTTP/1.1 403
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Credentials: true

That's correct behavior, not a bug: the preflight passing only means the browser is allowed to send the real request, not that the request will succeed. Here it fails on authentication, after CORS has already done its job. If the symptom you're chasing is "the preflight looks fine in the network tab but the real call still fails," the cause by this point is almost always missing credentials or a missing Authorization header, not CORS, even though the two produce near-identical red text in the console. A wrong origin still gets the same plain 403 Invalid CORS request from this configuration as it did without Security in the picture; that part of the behavior carries over unchanged.

The default max-age doesn't carry over either

One more difference between the two configs: building CorsConfiguration directly, the way the Security-integrated version above has to, doesn't set a maxAge unless you call config.setMaxAge(...) yourself. Our Security-backed responses above have no Access-Control-Max-Age header at all, where the plain CorsRegistry version defaulted to 1800 seconds without being asked. If you're moving an app from the first setup to the second because you added Spring Security, that's one line that's easy to drop without noticing, and the only symptom is an extra preflight on every request instead of one every 30 minutes.

When there's no Spring app to configure

Everything above assumes you own the backend and can add a bean to it. If the service you're calling from the browser is someone else's API with no Access-Control-Allow-Origin header and no Spring app for you to touch, a CORS proxy sits in front of it and answers the preflight itself instead. corsproxy.dev always responds with Access-Control-Allow-Origin: * and never sends Access-Control-Allow-Credentials, so it's built for calls that carry their own API key or token rather than ones that depend on cookies; a free key covers 100 requests a day for exactly that case.