• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

The Problem

Browsers enforce the Same-Origin Policy by default—scripts on domain A cannot access resources on domain B. This protects users from malicious cross-site requests, but blocks legitimate API calls between domains.

Core Idea

CORS (Cross-Origin Resource Sharing) is a mechanism that lets servers explicitly declare which domains (origins) can access their resources and under what conditions.

How It Works

Simple Request Flow

For simple requests (GET/POST/HEAD with standard headers):

  1. Client sends request with Origin header
  2. Server checks policy, responds with Access-Control-Allow-Origin
  3. Browser allows/blocks response based on header

Pre-flight Request Flow

For non-simple requests (PUT, DELETE, custom headers, non-standard Content-Type):

  1. Browser sends OPTIONS request first (pre-flight)
  2. Server responds with allowed methods, headers, and origins
  3. Browser caches this (via Access-Control-Max-Age)
  4. Then sends actual request

Key Headers

HeaderPurpose
OriginClient’s domain (sent by browser)
Access-Control-Allow-OriginAllowed origins (server)
Access-Control-Allow-MethodsAllowed methods (server)
Access-Control-Allow-HeadersAllowed headers (server)
Access-Control-Max-AgeCache duration for pre-flight
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
            .allowedOrigins("http://localhost:5173")
            .allowedMethods("GET", "POST", "PUT", "DELETE")
            .allowedHeaders("*")
            .allowCredentials(true);
    }
}

Key Properties

  • Server controls access—not the client
  • Pre-flight caching reduces overhead
  • Credentials require specific origin (not ’*’)

Connections

  • Related to: HTTP Headers (uses headers for negotiation: Access-Control-Allow-Origin)
  • Builds on: HTTP Methods (OPTIONS is the pre-flight method)
  • Related to: HTTP Status Codes (401, 403 errors appear in CORS failures)
  • Related to: Statelessness (CORS requests must include all auth per request)

Edge Cases & Gotchas

  • CORS errors in browser console ≠ server error; request reached server
  • Preflight required for PUT, DELETE, PATCH methods
  • Authorization header triggers pre-flight (custom header)
  • Misconfiguration appears as “blocked by CORS policy”