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?

工程师8 分钟流程模拟器代码挑战
httpbrowser-apisspring-securityangular

此挑战尚未翻译为简体中文,你正在阅读英文版本。

任务: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.

任务: Make the SPA's GET and JSON POST work with cookies, while a page on evil.example cannot read anything.

学习目标

  • Understand what CORS protects: reading responses in the browser.
  • Know the rules for credentials and wildcard origins.
  • Handle preflight requests before authentication.
模拟模拟数据
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();}

简化说明

Three representative requests and the browser's decision for each. 教学模型——数字用于说明行为,并非基准测试。

概念

相关挑战

参考资料