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

  1. Specify allowed origins: Set Access-Control-Allow-Origin to trusted domains. Avoid using * when credentials are involved.

  2. Restrict methods: Use Access-Control-Allow-Methods to expose only necessary HTTP verbs like GET and POST.

  3. Limit headers: Define Access-Control-Allow-Headers explicitly rather than reflecting client headers.

  4. Control credentials: If Access-Control-Allow-Credentials is true, never use wildcard origins.

  5. Set max age: Cache preflight responses with Access-Control-Max-Age to reduce OPTIONS overhead.

  6. 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.