Skip to content
Back to CurriculumLesson 26 of 30
resilience-securityIntermediate

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.

Interactive Visual Concept ExplainerStep-by-Step Educational Simulation
Visual Step-by-Step Concept Explainerresilience-security
Cross-Origin Resource Sharing (CORS): Preflights, Credential Restrictions & Safe API Sharing
Steps:
OPTIONS Preflight Handshake
1. Browser Dispatches OPTIONS:
Origin: https://app.cosmos.io
Access-Control-Request-Method: PUT
2. Server Inspects Whitelist:
Access-Control-Allow-Origin: https://app.cosmos.io
Handshake verified: Real PUT allowed!
Step 1 of 6
Auto-stepping (1x)

Step 1: Browser detects a cross-origin request involving non-simple headers or mutating HTTP methods.

Security Guarantee: CORS is a browser-side mechanism to relax the Same-Origin Policy; it is not server-side authorization.
Why This Architectural Concept Exists

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.

Intuitive Mental Model

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.

Architectural System TopologyProtocol Diagram
[ 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 Production Milestone

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-by-Step Execution Sequence
01

Step 1: Browser detects a cross-origin request involving non-simple headers or mutating HTTP methods.

02

Step 2: Browser automatically dispatches an HTTP OPTIONS preflight request before making the actual request.

03

Step 3: Server inspects the Origin header and checks it against an explicit allowlist of trusted origins.

04

Step 4: If trusted, server responds with Access-Control-Allow-Origin, Allow-Methods, Allow-Headers, and Max-Age.

05

Step 5: If credentials (cookies/auth headers) are required, server adds Access-Control-Allow-Credentials: true.

06

Step 6: Browser verifies the preflight response and executes the actual API request.

Production Architecture Blueprint
// 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;
}
Common Architectural Misconceptions
  • ✕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.
Common Architectural Pitfall

Blindly echoing back req.headers.Origin as Access-Control-Allow-Origin, effectively nullifying the Same-Origin Policy.

Production Best Practice Fix

Validate incoming origins against an explicit, immutable allowlist before setting the header.

Interactive Knowledge Check

Can an attacker bypass CORS restrictions by writing a Python script or using curl from their terminal?