CORS Fundamentals and Same-Origin Policy Relaxation
You'll learn how CORS enables controlled cross-origin requests while preserving security—and why getting it wrong opens dangerous holes.
What is CORS?
Cross-Origin Resource Sharing (CORS) is the security mechanism that relaxes the Same-Origin Policy in a controlled way. While SOP blocks JavaScript from accessing resources across different origins by default, CORS lets servers explicitly grant permission to specific cross-origin requests.
Think of SOP as a locked door between websites. CORS is the server handing out keys to trusted visitors—but only if the lock is properly configured.
How CORS Works
When your browser makes a cross-origin request, it sends an Origin header indicating where the request came from. The server responds with Access-Control-Allow-Origin to either approve or deny access:
Request Origin: https://app.example.com
Response: Access-Control-Allow-Origin: https://app.example.com
If the origins match (or the server allows wildcards), the browser permits JavaScript to read the response.
The Danger: Misconfigurations
CORS becomes a security disaster when misconfigured:
- Reflecting any origin: Server echoes the request's
Originheader back, trusting everyone - Wildcard with credentials: Combining
Access-Control-Allow-Origin: *withAccess-Control-Allow-Credentials: true(browsers block this, but legacy configs exist) - Weak origin validation: Checking if origin contains "trusted.com" matches "evil-trusted.com"
These mistakes effectively disable SOP protections, allowing malicious sites to read sensitive data from your API on behalf of authenticated users—similar to CSRF but with the ability to read responses.
Key Takeaway: CORS is a controlled relaxation of SOP that requires careful configuration; misconfigured CORS policies break the security boundary between origins, exposing sensitive data to unauthorized websites.