Security Risks of CORS Misconfigurations
How Cross-Origin Resource Sharing (CORS) prevents malicious websites from reading data from other domains, and the dangers of a wildcard policy.
Overview
Cross-Origin Resource Sharing (CORS) is an HTTP-header-based security mechanism implemented by all modern web browsers. It dictates whether a web application running at one origin (domain, scheme, or port) is permitted to access resources from a different origin.
The Problem
Browsers enforce the Same-Origin Policy (SOP). If a user logs into mybank.com, and then opens a malicious tab evil.com, SOP prevents the Javascript on evil.com from making an AJAX/Fetch request to read the user's account balance on mybank.com.
However, modern web architecture relies on separate domains (e.g., frontend.com calling api.backend.com). Because these are different origins, the browser blocks the frontend from reading the API response, breaking the application.
Solution and Configuration
Developers use CORS to tell the browser: "It is safe to let this specific external domain read my data." The backend API achieves this by sending specific HTTP Response Headers.
Correct Implementation (Node.js/Express):
const cors = require('cors');
app.use(cors({
origin: 'https://frontend.com',
credentials: true
}));
This adds Access-Control-Allow-Origin: https://frontend.com to the HTTP response.
Technical Details
The most catastrophic security vulnerability occurs when lazy developers try to fix CORS errors during development by setting the header to a wildcard: Access-Control-Allow-Origin: *. This completely disables the security boundary, allowing any website on the internet to read the API responses.
Another critical misconfiguration is when the server dynamically reflects the Origin header requested by the client. If an attacker sends Origin: https://evil.com, and the server blindly responds with Access-Control-Allow-Origin: https://evil.com with Access-Control-Allow-Credentials: true, the attacker can execute cross-origin requests, steal session cookies, and extract sensitive PII (Personally Identifiable Information) from the victim's browser.
Conclusion
CORS is not a defense for the server; it is a protection mechanism for the user's browser. API servers must strictly maintain an allowlist (whitelist) of trusted origins. Never use wildcards or blindly reflect headers in production environments involving authenticated endpoints.