The Real Fullstack

The CORS Confusion

Postman works, curl works, only the browser fails. And when it finally works, can evil.example read it too?

Ingénieur8 minSimulateur de fluxDéfi de code
httpbrowser-apisspring-securityangular

Ce défi n'est pas encore traduit en Français. Vous lisez la version anglaise.

Mission:Make the SPA's GET and JSON POST work with cookies, while a page on evil.example cannot read anything.Contexte · Objectifs d'apprentissage ▾

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.

Objectifs d'apprentissage

  • Understand what CORS protects: reading responses in the browser.
  • Know the rules for credentials and wildcard origins.
  • Handle preflight requests before authentication.
SimulationSimulé
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)
Lancer la simulation
@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();}

Simplification

Three representative requests and the browser's decision for each. Modèle pédagogique — les chiffres illustrent un comportement, ce ne sont pas des benchmarks.

Concepts

Défis liés

Références