The CORS Confusion
Postman works, curl works, only the browser fails. And when it finally works, can evil.example read it too?
Mission:Make the SPA's GET and JSON POST work with cookies, while a page on evil.example cannot read anything.
Larkspur moved its SPA to app.larkspur.example and its API to api.larkspur.example, with cookie-based sessions. Requests fail with CORS errors. A colleague found a snippet that reflects the Origin header back with credentials enabled — the console errors disappeared.
Mission: Make the SPA's GET and JSON POST work with cookies, while a page on evil.example cannot read anything.
Learning objectives
- Understand what CORS protects: reading responses in the browser.
- Know the rules for credentials and wildcard origins.
- Handle preflight requests before authentication.
SimulationSimulated
app.larkspur.example
1app GET /api/me (cookie) → blocked by browser (wildcard origin is not allowed with credentials)
2app POST /api/cart (JSON) → blocked by browser (OPTIONS preflight hit the auth filter → 401, no CORS headers)
evil.example
3evil GET /api/me (cookie) → blocked by browser (wildcard origin is not allowed with credentials)
@Bean SecurityFilterChain api(HttpSecurity http) throws Exception { return http .cors(c -> c.configurationSource(req -> { var cfg = new CorsConfiguration(); cfg.setAllowedOrigins(List.of("https://app.larkspur.example")); // explicit allow-list cfg.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE")); cfg.setAllowedHeaders(List.of("Content-Type", "X-XSRF-TOKEN")); cfg.setAllowCredentials(true); return cfg; })) // CorsFilter runs before authentication, .authorizeHttpRequests(a -> a.anyRequest().authenticated()) // so OPTIONS preflights get CORS headers .build();}