CORS Wildcards and Credential Handling
You'll learn: Why using wildcard origins with credentials is forbidden and how cookies change CORS security requirements.
Why Wildcards Seem Tempting
When configuring CORS, you might be tempted to allow all origins with Access-Control-Allow-Origin: *. This wildcard means "anyone from any website can read my responses." It's like leaving your front door wide open with a "come on in" sign.
The Credential Restriction
Here's the critical rule: you cannot use the wildcard * when credentials are involved. If your API needs to receive cookies, HTTP authentication, or client certificates, you must specify an exact origin.
This request header tells the browser to include credentials:
Access-Control-Allow-Credentials: true
But if you also set:
Access-Control-Allow-Origin: *
The browser will block the request. These two headers are mutually exclusive.
Why This Matters for Security
Credentials like cookies are automatically sent by the browser. If you allowed * with credentials, a malicious website could make authenticated requests to your API on behalf of logged-in users—a recipe for CSRF-style attacks.
Analogy: It's like having a keycard (cookie) that unlocks doors. You can either say "anyone can enter without a keycard" (wildcard) or "only people from approved companies can use their keycards" (specific origin + credentials), but not both.
When Cookies Are Included
Cookies are only sent cross-origin when:
- The request includes
credentials: 'include'(fetch API) - The server responds with
Access-Control-Allow-Credentials: true - The server specifies the exact requesting origin (not
*)
Key Takeaway: CORS wildcards and credentials cannot coexist—if you need authenticated cross-origin requests, you must whitelist specific origins and explicitly enable credential handling.