Sub topic 9
Configuring CORS for browser clients
This chapter assumes you can write a SecurityFilterChain bean (see the earlier chapters) and know basic HTTP headers. It covers what CORS is, how to configure it in Spring Security, and the errors that most often go wrong.
What CORS solves
Browsers apply the same-origin policy. A script loaded from https://app.example.com cannot read responses from https://api.example.com unless the API opts in. An origin is the combination of scheme, host and port. CORS (Cross-Origin Resource Sharing) is the opt-in mechanism, and it works through response headers such as Access-Control-Allow-Origin.
CORS is enforced by the browser. It does not stop curl, scripts or other servers from calling your API. It only controls which web pages may read your responses, so it never replaces authentication.
The preflight request
For requests that are not "simple", the browser first sends an OPTIONS request called a preflight. Requests count as non-simple when they use PUT or DELETE, or add headers such as Authorization. The preflight carries no credentials. If the server does not answer it correctly, the browser never sends the real request.
Why Spring Security needs to know
The security filter chain runs before Spring MVC. If CORS is configured only in MVC, the preflight reaches the security filters first. It has no credentials, so it is rejected with 401 and the browser reports a CORS failure. Calling http.cors(...) adds a CorsFilter early in the chain, so preflights are answered before authorization runs.
Defining the configuration
Declare a CorsConfigurationSource bean and enable cors() in the chain. With the bean present, Customizer.withDefaults() picks it up.
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@Configuration
public class CorsConfig {
@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"));
config.setMaxAge(3600L);
var source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", config);
return source;
}
@Bean
SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
http
.cors(Customizer.withDefaults())
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
}setMaxAge tells the browser to cache the preflight result for an hour, which cuts the number of OPTIONS calls. The path pattern /api/** limits the policy to API routes.
Common errors
- Preflight returns 401 or 403.
cors()is missing from the chain, or noCorsConfigurationSourcebean exists. - Wildcard origin with credentials.
setAllowedOrigins(List.of("*"))combined withsetAllowCredentials(true)throws anIllegalArgumentException. List explicit origins instead. - Header not allowed. If the client sends a header missing from
setAllowedHeaders, the preflight fails. A custom header such asX-Request-Idmust be listed. - Exact origin match.
http://localhost:3000andhttp://localhost:5173are different origins. Scheme and port must match exactly, with no trailing slash. - Response header unreadable. Scripts can read only a few headers by default. Add others with
setExposedHeaders.
Exercises
Exercise
A single-page app on https://app.example.com calls PUT /api/orders/1 with an Authorization header. The browser console shows a CORS error, and the server log shows an OPTIONS request rejected with 401. What is the likely cause, and what is the fix?
Show answer
Spring Security rejected the credential-less preflight before CORS handling ran. Add http.cors(Customizer.withDefaults()) to the SecurityFilterChain and define a CorsConfigurationSource bean that allows the origin, the PUT method and the Authorization header.
Exercise
Why does setAllowedOrigins(List.of("*")) together with setAllowCredentials(true) fail, and what should you do instead?
Show answer
Browsers do not accept a wildcard origin on credentialed requests, so Spring rejects the combination with an IllegalArgumentException. List the exact origins, such as https://app.example.com, instead.