CORS Security Configuration
A browser mechanism that allows controlled access to resources from a different origin than the serving domain.
Description
Cross-Origin Resource Sharing (CORS) is a security mechanism enforced by browsers that controls how web pages from one origin can request resources from another origin. The same-origin policy, a fundamental browser security model, restricts scripts from making requests to a different domain, protocol, or port. CORS provides a standardized way to relax this restriction selectively, enabling legitimate cross-origin requests while blocking unauthorized ones.
CORS works through a system of HTTP headers. When a browser makes a cross-origin request, it sends an Origin header. The server responds with Access-Control-Allow-Origin specifying which origins are permitted. For non-simple requests (those with custom headers, non-standard methods, or certain content types), the browser sends a preflight OPTIONS request to check permissions before the actual request. The server responds with allowed methods, headers, and whether credentials are permitted.
Misconfigured CORS is a frequent source of security vulnerabilities. Common mistakes include setting Access-Control-Allow-Origin to * (wildcard) while also allowing credentials, dynamically reflecting the Origin header without validation (effectively allowing any origin), and overly broad Allow-Headers or Allow-Methods settings. Secure configuration requires an explicit allowlist of trusted origins, restrictive method and header lists, careful credential handling, and appropriate preflight cache durations.
Prompt Snippet
Configure CORS with an explicit origin allowlist rather than wildcard (*) or dynamic Origin reflection. Set Access-Control-Allow-Origin to specific trusted domains, enable Access-Control-Allow-Credentials only when cookie/auth-based flows require it, and restrict Access-Control-Allow-Methods to the minimum set (GET, POST, OPTIONS). In Express, use the cors middleware with a validated origin function that checks against a Set of permitted origins. Set Access-Control-Max-Age to 86400 to cache preflight responses and reduce OPTIONS request overhead. Never expose sensitive headers via Access-Control-Expose-Headers without explicit need.
Tags
Related Terms
Security Headers
HTTP response headers that instruct browsers to enable security mechanisms, reducing the attack surface of web applications.
HTTPS Enforcement (HSTS)
Mechanisms that ensure all communication occurs over encrypted HTTPS connections, preventing protocol downgrade attacks.
Secure Cookie Configuration
Properly configuring cookie attributes to prevent theft, tampering, and misuse of session and authentication cookies.