Course contentsShow
← Security
Lesson 864 of 3,05218. Web Security - CSRF and Request ForgeryFree lesson

CORS Security Best Practices

Implementing secure CORS configurations with allowlist validation, proper credential handling, and defense against common misconfigurations.

CORS Security Best Practices

You'll learn: How to configure CORS securely to prevent attackers from exploiting misconfigurations that could expose your API to unauthorized cross-origin requests.

Core Idea

Cross-Origin Resource Sharing (CORS) is powerful but dangerous when misconfigured. Secure CORS requires three pillars: strict origin validation using allowlists, careful credential handling, and avoiding common pitfalls that attackers love to exploit.

The Three Pillars of Secure CORS

1. Allowlist-Based Origin Validation

Never reflect the Origin header directly or use wildcard (*) with credentials. Instead, maintain an explicit allowlist of trusted origins:

// Check incoming Origin against your allowlist
If request Origin is "https://trusted-app.com":
    Set Access-Control-Allow-Origin: https://trusted-app.com
Else:
    Reject or omit CORS headers

Think of it like a bouncer checking IDs: only people on the guest list get in, no exceptions.

2. Proper Credential Handling

When using Access-Control-Allow-Credentials: true, never use wildcard origins. Always specify the exact origin and validate it server-side first.

3. Defense Against Common Mistakes

  • No null origin acceptance – attackers easily forge this
  • No dynamic origin reflection – don't blindly echo back the Origin header
  • No regex weaknesses – evil.com shouldn't match if you meant app.com
  • Minimize exposed headers and methods – only allow what's necessary
  • Set short preflight cache times – limit Access-Control-Max-Age

Real Protection Strategy

Validate origins before setting CORS headers. Use exact string matching or carefully tested regex patterns. Log rejected cross-origin attempts for monitoring.

Key Takeaway: Secure CORS requires explicit origin allowlists, never mixing credentials with wildcards, and validating every origin server-side before granting access—treat CORS configuration as security-critical code, not boilerplate.