Credentials and CORS: Access-Control-Allow-Credentials
You'll learn: Why browsers require explicit permission to send credentials cross-origin and why wildcards break this security boundary.
The Credential Problem in Cross-Origin Requests
By default, CORS requests don't include credentials like cookies, authorization headers, or TLS client certificates. This is a critical security feature: if your browser automatically sent your banking cookies to every cross-origin request, any malicious site could impersonate you.
To explicitly allow credentials in a CORS request, both the client and server must opt in:
- Client side: The request must set
credentials: 'include'(in JavaScript fetch) orwithCredentials: true(in XMLHttpRequest) - Server side: The response must include
Access-Control-Allow-Credentials: true
Why Wildcards Fail with Credentials
Here's the crucial security rule: You cannot use Access-Control-Allow-Origin: * (wildcard) together with Access-Control-Allow-Credentials: true.
Think of it like a bouncer at an exclusive club. The wildcard says "anyone can enter," while credentials say "verify their membership card." These two instructions contradict each other—if anyone can enter, there's no point checking credentials.
When credentials are involved, the server must specify the exact origin:
Access-Control-Allow-Origin: https://trusted-site.com
Access-Control-Allow-Credentials: true
If you try combining wildcards with credentials, the browser will block the response entirely, protecting users from accidentally exposing their authentication to arbitrary sites.
This prevents a dangerous scenario where a malicious site at evil.com could make credentialed requests to your API and receive responses with your users' cookies attached.
Key Takeaway: Credentialed CORS requires explicit origin trust—wildcards are forbidden because they would allow any site to make authenticated requests on behalf of your users.