How to configure CORS securely for web APIs
· Category: Cybersecurity
Short answer
CORS allows web browsers to make cross-origin requests while giving servers control over which origins, methods, and headers are permitted.
Steps
-
Specify allowed origins: Set
Access-Control-Allow-Originto trusted domains. Avoid using*when credentials are involved. -
Restrict methods: Use
Access-Control-Allow-Methodsto expose only necessary HTTP verbs like GET and POST. -
Limit headers: Define
Access-Control-Allow-Headersexplicitly rather than reflecting client headers. -
Control credentials: If
Access-Control-Allow-Credentialsis true, never use wildcard origins. -
Set max age: Cache preflight responses with
Access-Control-Max-Ageto reduce OPTIONS overhead. -
Validate server-side: CORS is a browser convenience, not a security boundary. Always enforce authorization independently.
Tips
- Use an allowlist rather than parsing and validating origins dynamically.
- Enable CORS only on endpoints that need it.
- Log unexpected cross-origin requests for threat detection.
Common issues
- Wildcard origins combined with credentials creating security holes.
- Overly permissive preflight responses allowing unintended methods.
- Relying on CORS alone to protect sensitive data.