CORS Security Best Practices and Defense
You'll learn how to configure CORS securely by implementing strict origin whitelisting, robust validation patterns, and hardened configurations that prevent cross-origin attacks.
The Core Idea
After understanding CORS vulnerabilities (origin reflection, wildcard misuse, null origins), you need to lock down your CORS implementation with defensive patterns. Think of CORS configuration like a nightclub's VIP list—you need an explicit, maintained whitelist of trusted origins, strict validation that can't be fooled by lookalike domains, and rules that never accidentally grant access to unauthorized guests.
Security Best Practices
1. Explicit Origin Whitelisting
Never dynamically reflect origins without validation. Maintain a hardcoded list of allowed origins:
const ALLOWED_ORIGINS = [
'https://app.example.com',
'https://mobile.example.com'
];
if (ALLOWED_ORIGINS.includes(requestOrigin)) {
response.setHeader('Access-Control-Allow-Origin', requestOrigin);
}
2. Exact Match Validation
Avoid regex patterns or substring matching that attackers can bypass. Use strict equality checks to prevent evil-example.com from matching example.com.
3. Never Use Wildcards with Credentials
Never combine Access-Control-Allow-Origin: * with Access-Control-Allow-Credentials: true—browsers block this, but dynamic reflection creates the same vulnerability.
4. Validate Before Setting Headers
Check origins before your application logic runs, not after. Reject invalid origins early with proper HTTP status codes (403 Forbidden).
5. Audit and Monitor
Regularly review your whitelist. Remove unused origins. Log CORS rejections to detect attack attempts.
Key Takeaway:
CORS security requires explicit origin whitelists with exact-match validation, never reflecting origins dynamically or mixing wildcards with credentials—treat CORS configuration as a critical security boundary, not a convenience feature.