Sub topic 9
Configuring CORS for browser clients
This chapter assumes you can build REST controllers with Spring Boot, read a SecurityFilterChain bean, and recognize the basic HTTP headers. You should also know the difference between authentication and authorization from earlier chapters.
Why CORS exists
Browsers enforce the same-origin policy. A page loaded from one origin can't read responses from a different origin. An origin is the combination of scheme, host and port. These are three different origins:
https://app.example.comhttps://api.example.comhttps://app.example.com:8443
CORS (Cross-Origin Resource Sharing) is the mechanism that lets a server tell the browser which other origins may read its responses. Suppose a single-page app at https://app.example.com calls your API at https://api.example.com. The browser blocks the page from reading the response unless your API sends the right CORS headers.
CORS is enforced by the browser, not by your server. curl, Postman and other servers ignore it. It does not protect your API from anyone. It controls which web pages in a user's browser may read your API's responses. You still need authentication and authorization on every endpoint.
Simple requests and preflight requests
The browser sends some cross-origin requests directly. These are "simple" requests: GET, HEAD or POST with only basic headers and content types. Everything else triggers a preflight. A preflight is an OPTIONS request the browser sends first to ask whether the real request is allowed.
A request with an Authorization header or a JSON body (Content-Type: application/json) is not simple. A typical API call from a browser therefore triggers a preflight.
The preflight carries these request headers:
Origin: the page's origin.Access-Control-Request-Method: the method the real request will use.Access-Control-Request-Headers: the custom headers the real request will send.
The server answers with Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers and optionally Access-Control-Max-Age. If anything doesn't match, the browser never sends the real request.
Why Spring Security needs to know about CORS
Browsers don't send credentials such as an Authorization header or cookies on a preflight. So a preflight arrives unauthenticated. If Spring Security's filter chain rejects it with 401 before Spring MVC can add CORS headers, the browser reports a CORS failure. The real cause is a security rule.
Spring Security solves this with its CorsFilter. It runs early in the chain, before the authorization checks. It answers preflights itself and adds the CORS headers to actual responses. You enable it by calling http.cors(...) in the filter chain.
Defining a CorsConfigurationSource bean
A CorsConfigurationSource maps URL patterns to CorsConfiguration objects. Declare it as a bean. When you call http.cors(Customizer.withDefaults()), Spring Security looks up that bean and uses it.
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@Bean
CorsConfigurationSource corsConfigurationSource() {
var config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://app.example.com"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
var source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", config);
return source;
}
// In the SecurityFilterChain: http.cors(Customizer.withDefaults());Here is the full filter chain with CORS enabled. It builds on the stateless API configuration from earlier chapters:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
http
.cors(Customizer.withDefaults())
.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/orders/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
}The CorsFilter is placed ahead of authentication and authorization filters. That placement is why preflights succeed without credentials while the real requests are still checked.
What each setting does
| Setting | Controls | Response header |
|---|---|---|
| `setAllowedOrigins` | Which origins may read responses | `Access-Control-Allow-Origin` |
| `setAllowedMethods` | Methods allowed on the real request | `Access-Control-Allow-Methods` |
| `setAllowedHeaders` | Request headers the page may send | `Access-Control-Allow-Headers` |
| `setExposedHeaders` | Response headers the page's JavaScript may read | `Access-Control-Expose-Headers` |
| `setAllowCredentials` | Whether cookies and similar credentials are allowed | `Access-Control-Allow-Credentials` |
| `setMaxAge` | How long the browser may cache the preflight result | `Access-Control-Max-Age` |
Some details matter in practice:
- Exact origin matching. An origin is matched as a whole string.
https://app.example.comdoes not matchhttp://app.example.comorhttps://app.example.com:8443. A trailing slash in the configured value also breaks the match. - Exposed headers. By default, browser JavaScript can read only a small set of "safe" response headers. If your API returns a custom header such as
Locationfor pagination links orX-Total-Count, add it withsetExposedHeaders. - Preflight caching. Calling
config.setMaxAge(3600L)lets the browser reuse a preflight result for up to an hour, which cuts the number ofOPTIONSrequests. Browsers cap this value, often at a few hours or less.
Credentials and wildcards
The setAllowCredentials(true) option allows the browser to include cookies and HTTP authentication in cross-origin requests, and to expose the response to the page. With a bearer token held in JavaScript memory and sent in an Authorization header, you usually don't need it. You need it when the browser must send cookies, such as a session cookie or a cookie-based CSRF token.
The browser rules for credentialed requests are strict. The server must not answer with * for the allowed origin, methods or headers. Spring enforces this: calling setAllowCredentials(true) together with setAllowedOrigins(List.of("*")) throws an IllegalArgumentException when the configuration is validated. If you need pattern-based origins with credentials, use setAllowedOriginPatterns:
var config = new CorsConfiguration();
config.setAllowedOriginPatterns(List.of("https://*.example.com"));
config.setAllowedMethods(List.of("GET", "POST"));
config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
config.setAllowCredentials(true);With a pattern, Spring echoes the matching request origin back in Access-Control-Allow-Origin. That is different from sending *, and it is why the combination is legal. It also means any subdomain matching the pattern can make credentialed calls. Treat every subdomain you list as trusted. A forgotten or hijacked subdomain then becomes a way into your API.
Choosing between configuration styles
You can set CORS up in several places. They behave differently with Spring Security.
| Approach | Works with Spring Security's `CorsFilter` | Notes |
|---|---|---|
| `CorsConfigurationSource` bean plus `http.cors(...)` | Yes | Recommended. Covers preflights and security-rejected responses. |
| `@CrossOrigin` on controllers | Only if `http.cors(...)` is also enabled | Spring Security delegates to MVC's handler mapping when no source bean exists. Per-controller rules scatter policy. |
| `WebMvcConfigurer.addCorsMappings` | Same as above | Convenient, but the policy lives apart from security rules. |
| `http.cors(c -> c.configurationSource(...))` | Yes | Inline alternative to the bean. |
Keeping one CorsConfigurationSource bean means a single place to review which origins can call the API.
Common errors and how to diagnose them
Most CORS problems appear in the browser console, not in your server logs. Use the browser's network tab and look at the OPTIONS request.
- Preflight returns 401 or 403. Spring Security is not using the CORS configuration. Check that
http.cors(...)is present and that aCorsConfigurationSourcebean exists. - Response has no
Access-Control-Allow-Originheader. The request'sOrigindoesn't match any allowed origin. Compare scheme, host and port character by character. - "Request header field authorization is not allowed." Add
AuthorizationtosetAllowedHeaders. - "Method PUT is not allowed." Add the method to
setAllowedMethods. - Credentials error with a wildcard. The browser rejects
Access-Control-Allow-Origin: *on credentialed requests. Use explicit origins or origin patterns. - The page reads a response but a header is
null. The header isn't exposed. Add it withsetExposedHeaders. - A 401 on a real request shows up as a CORS error. If the error response itself has no CORS headers, the browser hides the status. With
http.cors(...)active, Spring Security adds the headers to these responses too, so you see the real 401.
You can also reproduce a preflight from the command line to see exactly what the server returns:
curl -i -X OPTIONS http://localhost:8080/api/orders \
-H "Origin: https://app.example.com" \
-H "Access-Control-Request-Method: GET" \
-H "Access-Control-Request-Headers: authorization"A correct configuration returns a 200 status with the Access-Control-Allow-* headers. If the origin is not allowed, Spring responds with 403 and the body Invalid CORS request.
Per-environment origins
Hard-coding the production origin makes local development awkward, because a dev server often runs at http://localhost:3000. Read the allowed origins from configuration instead:
app.cors.allowed-origins=https://app.example.com,http://localhost:3000@Bean
CorsConfigurationSource corsConfigurationSource(
@Value("${app.cors.allowed-origins}") List<String> origins) {
var config = new CorsConfiguration();
config.setAllowedOrigins(origins);
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
config.setMaxAge(3600L);
var source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", config);
return source;
}Spring converts the comma-separated property into a List<String>. Keep localhost entries out of the production profile.
How CORS relates to CSRF
CORS and CSRF are separate. CORS controls which origins may read responses. It does not stop a malicious page from sending a request, and simple cross-origin requests such as a form POST reach your server regardless. CSRF protection, covered in the previous chapter, defends against that. A stateless API using bearer tokens in the Authorization header can disable CSRF protection because the browser doesn't attach those tokens automatically. CORS stays relevant either way, since browser clients still need permission to read responses.
Exercise
A single-page app at https://app.example.com calls GET /api/orders with an Authorization header. The browser console reports a CORS error, and the network tab shows the OPTIONS preflight returned 401. Your CorsConfigurationSource bean allows the origin, method and header. What is the most likely cause, and what is the fix?
Show answer
The filter chain does not call http.cors(...), so Spring Security's CorsFilter never handles the preflight. The preflight carries no credentials, so the authorization rules reject it with 401 before any CORS headers are added. Add http.cors(Customizer.withDefaults()) to the SecurityFilterChain so the CorsFilter answers preflights ahead of authorization.
Exercise
You set setAllowedOrigins(List.of("*")) and setAllowCredentials(true) so the app can send cookies from any subdomain of example.com. What happens, and what should you use instead?
Show answer
Spring rejects the combination with an IllegalArgumentException, and browsers refuse a wildcard origin on credentialed requests anyway. Use setAllowedOriginPatterns(List.of("https://*.example.com")) or, better, list the exact origins. Only include subdomains you trust, because each one can make credentialed calls.