Cross-Origin Resource Sharing (CORS)
Master simple requests, preflight OPTIONS handshakes, and credential hazards.
CORS is a W3C standard protocol that relaxes the Same-Origin Policy in a controlled way, allowing servers to declare which cross-origin applications are permitted to read their private API responses.
A common misconfiguration is reflecting arbitrary `Origin` headers into `Access-Control-Allow-Origin` while setting `Access-Control-Allow-Credentials: true`, completely bypassing SOP for authenticated sessions.
Strictly validate the request `Origin` header against an allowlist of trusted origins before echoing it. Never combine `Access-Control-Allow-Origin: *` with credentials.
Technical Deep Dive
Simple vs Preflighted Requests
Requests using GET, POST, or HEAD with standard headers (Accept, Content-Type: application/x-www-form-urlencoded, multipart/form-data, text/plain) are Simple Requests. If a request uses PUT, DELETE, custom headers (like Authorization), or Content-Type: application/json, the browser MUST first dispatch an OPTIONS preflight request.
Critical CORS Response Headers
Click a real-world scenario to see how the 5 core headers are configured and evaluated by the browser.
https://app.example.comtrueGET, POST, PUT, DELETE, OPTIONSContent-Type, Authorization86400 (24h cache)Interactive Mental Model Simulation
Live VisualizerCode Implementation & Patching
// Express.js Vulnerability: Blind Origin Reflection with Credentials
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', req.headers.origin || '*');
res.setHeader('Access-Control-Allow-Credentials', 'true'); // Critical flaw: any malicious site can steal user data!
next();
});// Secure CORS Configuration with Strict 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('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Access-Control-Max-Age', '86400');
}
next();
});Always maintain an immutable Set of authorized origins. Never use regex without anchoring (^ and $) or reflect arbitrary Origin headers when credentials are enabled.
Test Your Knowledge on Cross-Origin Resource Sharing (CORS)
Challenge yourself with realistic scenario questions in the Web Security Arena.