What exactly does the Access-Control-Allow-Credentials header do?

I'm trying to understand how to use CORS and am confused about what the Access-Control-Allow-Credentials header does.

The documentation says

Indicates whether or not the response to the request can be exposed when the credentials flag is true.

But I don't understand what the response being "exposed" means.

Can anyone explain what this header being set to true (in conjunction with the credentials flag being set to true) actually does?


Solution 1:

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).