CORS Protocol Deep-Dive: Preflight OPTIONS requests, credentialed origins, and the wildcard credential trap.
Cross-Origin Resource Sharing (CORS) Mechanics
CORS is not an API firewall—it is a browser-enforced relaxation of the Same-Origin Policy (SOP) that permits web applications on one origin (e.g., https://app.com) to access resources from a different origin (e.g., https://api.com).
Client (https://app.com) Server (https://api.com)
| |
| 1. Preflight OPTIONS /api/data |
| Origin: https://app.com |
| Access-Control-Request-Method: POST |
| Access-Control-Request-Headers: Content-Type, Auth |
|---------------------------------------------------------->|
| |
| 2. Preflight Response |
| Access-Control-Allow-Origin: https://app.com |
| Access-Control-Allow-Methods: POST, GET, OPTIONS |
| Access-Control-Allow-Credentials: true |
| Access-Control-Max-Age: 86400 (Cache 24h) |
|<----------------------------------------------------------|
| |
| 3. Actual Request (POST /api/data with Session Cookie) |
|---------------------------------------------------------->|
The Critical Wildcard Credential Vulnerability Trap
Severe Vulnerability: Setting
Access-Control-Allow-Origin: *while attempting to authenticate requests.Browsers strictly block responses if
Access-Control-Allow-Credentials: trueis paired with a wildcard*origin.Dangerous Anti-Pattern: Echoing back whatever
Originheader the client sends without an allowlist.Secure Implementation: Validate incoming
Originagainst a strict compile-time server allowlist:
const ALLOWED_ORIGINS = new Set(['https://app.example.com', 'https://admin.example.com']);
app.use((req, res, next) => {
const origin = req.headers.origin;
if (origin && ALLOWED_ORIGINS.has(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Vary', 'Origin'); // Critical for HTTP caching!
}
next();
});