XHR2 withCredentials - which cookies are sent?

2019-08-26 04:32发布

问题:

Hopefully this is simple to answer.

With a credentialed request in XHR2, which cookies are sent?

I've been following the MDN article on credentialed requests, and it shows that the cookie pageAccess=2 is sent with the request. However it doesn't explain where that cookie comes from, and why that cookie specifically is being sent. Is it simply that all cookies set by the page are sent in any credentialed request?

回答1:

From the HTML5 Rocks page on CORS:

The .withCredentials property will include any cookies from the remote domain in the request, and it will also set any cookies from the remote domain.

I assume "any cookies" means "all cookies" (probably subject to a HTTPS-only flag on the cookie), since there is no mechanism to specify cookies with XHR2.

The cookies that get sent are the cookies that were set by the remote domain: if foo.com sends a request a credentialed request to bar.com, any cookies set by bar.com are sent. To put this in practical terms, suppose facebook.com has a CORS-aware API that requires you to be logged in to use. I've logged in to Facebook earlier in my browser session, but now I'm browsing foo.com, which is going to use Facebook's API on my behalf. foo.com asks th ebrowser to send a cross-domain request to facebook.com along with all my facebook.com cookies so Facebook knows who I am and that I've already authenticated to Facebook.