Gibarian2001 Gibarian2001 - 23 days ago 8
Javascript Question

Is CORS a secure way to do cross-domain AJAX requests?

After reading about CORS (Cross-Origin Resource Sharing), I don't understand how it improves security. Cross-Domain AJAX communication is allowed if the correct ORIGIN header is sent. As an example, if I send

ORIGIN: http://mysite.com

The server checks if this domain is in the white list and, if it is, header:

Access-Control-Allow-Origin: [received url here]

is sent back, together with the response (This is the simple case, there are also prefighted requests, but the question is the same).

¿Is this really secure? If someone wants to receive the information, faking an ORIGIN headers seems like a really trivial task. Also the standard says that the policy is enforced in the browser, blocking the response if Access-Control-Allow-Origin is not correct. Obviously if anyone is trying to get that info, he will not use a standard browser to block it.

Answer

It isn't designed to stop people getting the data. You can't expose it without people getting it.

It is designed so that given:

  • Alice, a person providing an API designed to be accessed via Ajax
  • Bob, a person with a web browser
  • Charlie, a third party running their own website

If Bob visits Charlie's website, then Charlie cannot send JS to Bob's browser so that it fetches data from Alice's website and sends it to Charlie.

The above situation becomes more important if Bob has a user account on Alice's website which allows him to do things like post comments or delete data — since without protection, Charlie could tell Bob's browser to do that behind Bob's back.

If you want to stop unauthorized people from seeing the data, then you need to protect with passwords, SSL client certs or some other means of identity based authentication/authorization.