Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:*?

like image 919
electrotype Avatar asked Oct 30 '22 04:10

electrotype


1 Answers

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.

like image 61
Quentin Avatar answered Nov 13 '22 14:11

Quentin