Cross-Origin Resource Sharing (CORS)
Configuration Reference
| Header | Purpose | Example |
|---|---|---|
| Access-Control-Allow-Origin | Allowed origins | https://app.example.com |
| Access-Control-Allow-Methods | Allowed HTTP methods | GET, POST, PUT |
| Access-Control-Allow-Headers | Allowed request headers | Content-Type, Authorization |
| Access-Control-Allow-Credentials | Allow cookies/auth | true |
| Access-Control-Max-Age | Preflight cache duration | 86400 |
Why CORS Is Important
CORS exists to prevent malicious websites from making requests to your API on behalf of a user without their knowledge. Without the Same-Origin Policy and CORS, a malicious page could use JavaScript to read data from your banking API using the user's session cookies.
Misconfigured CORS is a common security vulnerability. Setting Access-Control-Allow-Origin: * allows any website to make requests to your API. If your API uses cookies or authentication, this is dangerous because any malicious site could make authenticated requests. Only allow specific, trusted origins.
The most dangerous misconfiguration is reflecting the request's Origin header back as Access-Control-Allow-Origin combined with Access-Control-Allow-Credentials: true. This allows any site to make authenticated cross-origin requests to your API. Always validate the Origin header against a whitelist of trusted domains.
Checking Your Setup
A security audit checks your server's CORS headers. Verify that Access-Control-Allow-Origin is not set to * if your API uses authentication. Check that only trusted origins are allowed and that Access-Control-Allow-Credentials is not combined with a wildcard origin.