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. نموذج تعليمي — الأرقام توضّح سلوكًا وليست قياسات أداء.

المفاهيم

تحديات ذات صلة

المراجع