electrotype electrotype - 7 months ago 22
Javascript Question

CORS - How can the server know if Jquery ajax's "withCredentials : true" was used?

I'm implementing CORS (Cross-origin resource sharing) in a framework.

I know that when an XMLHttpRequest request is made using Jquery's

ajax(...)
and the
withCredentials
property is
true
, the server must respond those two things:


  • Access-Control-Allow-Credentials: true

  • Access-Control-Allow-Origin:[THE_DOMAIN]



The server can't response with a wildcard,
Access-Control-Allow-Origin:*
: that doesn't work!

My question: how do I know, on the server, that
withCredentials: true
has been used, so I don't use the wildcard?

I compared the headers sent when using
withCredentials: false
and when using
withCredentials: true
and they are identical!

So, if I do want to allow credentials when the client requests it, does it mean I can't, ever, use
Access-Control-Allow-Origin:*
?

Answer

So, if I do want to allow credentials when the client requests it, does it mean I can't, ever, use Access-Control-Allow-Origin:*?

Yes.

The point of Access-Control-Allow-Origin:* is that it lets you, with very little effort, grant access to every website. It lets you say "This data is public and anyone can access it".

If you require credentials to access the resource, then it doesn't make sense to say "This data is public and anyone can access it".

If you were to grant access to every website, then every website visited by someone logged into your site could read the data from it (effectively making it public).

So, you need to have a whitelist of trusted sites that are allowed to access the data and then check the Origin header before explicitly granting access to them.