Handling Credentials in CORS
Swipe um das Menü anzuzeigen
Credentialed requests in CORS involve sending cookies, HTTP authentication, or client-side SSL certificates along with the request. These credentials are often essential for user sessions and secure APIs. Browsers treat credentialed requests with extra caution because they can expose sensitive information if not handled correctly. To enable credentials in cross-origin requests, you must configure both the frontend and backend, but the backend plays a critical role in ensuring credentials are only shared with trusted origins.
When a browser sends a credentialed cross-origin request, it expects the backend to explicitly allow credentials. This cannot be done with the default CORS configuration. If the backend does not allow credentials, the browser will strip cookies and authentication headers from the request, and the response will not be accessible to JavaScript on the client.
To enable credentials, the backend must include the Access-Control-Allow-Credentials: true header in its response. However, this header alone is not enough. The Access-Control-Allow-Origin header must also be set to a specific origin, not to the wildcard (*). This is because allowing credentials with a wildcard origin would create a significant security risk, enabling any site to access sensitive data.
The interaction between these two headers is strict:
- If
Access-Control-Allow-Credentialsis set totrue, thenAccess-Control-Allow-Origincannot be*; - The origin must match the requesting site exactly;
- If these headers are not set correctly, browsers will block the response or strip credentials.
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://trusted.example.com
Access-Control-Allow-Credentials: true
Content-Type: application/json
{
"user": "alice",
"role": "admin"
}
In this example, the backend responds to a credentialed request from https://trusted.example.com. The Access-Control-Allow-Origin header is set to that specific origin, and Access-Control-Allow-Credentials is set to true. This combination tells the browser it is safe to include cookies or authentication information in the request and to make the response available to JavaScript running on that origin.
You cannot use Access-Control-Allow-Origin: * together with Access-Control-Allow-Credentials: true. Browsers will reject such a response, and credentials will not be included or exposed. This restriction prevents sensitive data from being shared with any origin, which would be a serious security vulnerability.
Danke für Ihr Feedback!
Fragen Sie AI
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen