Cross-Origin Resource Sharing (CORS): Preflights, Credential Restrictions & Safe API Sharing
Cross-Origin Resource Sharing (CORS) is a browser security mechanism that relaxes the Same-Origin Policy (SOP) to allow web applications to query APIs on different origins. Safe CORS configuration requires explicit origin whitelisting, correct handling of preflight OPTIONS requests, and strictly avoiding 'Access-Control-Allow-Origin: *' with credentials.
Step 1: Browser detects a cross-origin request involving non-simple headers or mutating HTTP methods.
Browsers restrict scripts on one origin (app.domain.com) from reading responses from another origin (api.domain.com) by default. APIs must selectively permit trusted client origins to read data while preventing malicious origins (evil.com) from harvesting authenticated responses.
The Embassy Courier Clearance: When a messenger arrives at a foreign embassy with an official package, the guards don't open the door immediately. They first send an advance radio query (OPTIONS preflight) asking the front desk if messengers from that specific country are permitted to exchange documents.
[ Browser on https://app.cosmos.app ] [ API on https://api.cosmos.app ]
│ │
├── (1) Preflight: OPTIONS /api/data ──────────►│
│ Origin: https://app.cosmos.app │
│ Access-Control-Request-Method: DELETE │
│ ├── Check Origin against Whitelist
│◄── (2) 204 No Content ────────────────────────┤
│ Access-Control-Allow-Origin: https://app.cosmos.app
│ Access-Control-Allow-Credentials: true
│ Access-Control-Allow-Methods: GET, POST, DELETE
│
├── (3) Actual Request: DELETE /api/data ──────►│
│ (with HttpOnly session cookies) │
│◄── (4) 200 OK { success: true } ──────────────┤CosmosApp hosts its web application at https://cosmos.app and its GraphQL API at https://api.cosmos.app. Because the origins differ, CosmosApp's API configures an exact CORS origin whitelist. It explicitly permits https://cosmos.app with credentials allowed, but strictly rejects requests originating from unauthorized third-party domains.
Step 1: Browser detects a cross-origin request involving non-simple headers or mutating HTTP methods.
Step 2: Browser automatically dispatches an HTTP OPTIONS preflight request before making the actual request.
Step 3: Server inspects the Origin header and checks it against an explicit allowlist of trusted origins.
Step 4: If trusted, server responds with Access-Control-Allow-Origin, Allow-Methods, Allow-Headers, and Max-Age.
Step 5: If credentials (cookies/auth headers) are required, server adds Access-Control-Allow-Credentials: true.
Step 6: Browser verifies the preflight response and executes the actual API request.
// CosmosApp Production CORS Middleware:
const ALLOWED_ORIGINS = new Set([
'https://cosmos.app',
'https://staging.cosmos.app',
]);
export function handleCors(req: Request): Headers {
const origin = req.headers.get('Origin');
const headers = new Headers();
if (origin && ALLOWED_ORIGINS.has(origin)) {
headers.set('Access-Control-Allow-Origin', origin);
headers.set('Access-Control-Allow-Credentials', 'true');
headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-CSRF-Token');
headers.set('Access-Control-Max-Age', '86400'); // Cache preflight for 24 hours
headers.set('Vary', 'Origin'); // Prevent caching origin collisions
}
return headers;
}- ✕CORS protects the server from malicious requests (CORS is purely a browser enforcement mechanism; curl, mobile apps, and scripts bypass CORS completely).
- ✕Setting Access-Control-Allow-Origin: * with credentials is supported (Browsers explicitly reject responses combining wildcard origins with Allow-Credentials: true).
Key Architectural Takeaways
- ✓CORS is a browser-side mechanism to relax the Same-Origin Policy; it is not server-side authorization.
- ✓Never reflect the untrusted incoming Origin header blindly into Access-Control-Allow-Origin.
- ✓Always set the Vary: Origin header when dynamically generating CORS headers to prevent cache poisoning.
Blindly echoing back req.headers.Origin as Access-Control-Allow-Origin, effectively nullifying the Same-Origin Policy.
Validate incoming origins against an explicit, immutable allowlist before setting the header.
Can an attacker bypass CORS restrictions by writing a Python script or using curl from their terminal?