Is CORS a secure way to do cross-domain AJAX requests?
The purpose is to prevent this -
- You go to website X
- The author of website X has written an evil script which gets sent to your browser
- that script running on your browser logs onto your bank website and does evil stuff and because it's running as you in your browser it has permission to do so.
The ideas is that your bank's website needs some way to tell your browser if scripts on website X should be trusted to access pages at your bank.
Just to add on @jcoder 's answer, the whole point of the Origin
header isn’t to protect the resources requested on a server. That task is up to the server itself via other means exactly because an attacker is indeed able to spoof this header with the appropriate tools.
The point of the Origin
header is to protect the user.
The scenario is the following:
an attacker creates a malicious website M
a user Alice is tricked to connect to M, which contains a script that tries to perform some actions through CORS on a server B that actually supports CORS
B will probably not have M in its
Access-Control-Allow-Origin
header, cause why would it?The pivotal point is that M has no means to spoof or overwrite the
Origin
header, because the requests are initiated by Alice's browser. So her browser will set the (correct)Origin
to M, which is not in theAccess-Control-Allow-Origin
of B, therefore the request will fail.
Alice could alter the Origin
header herself, but why would she, since it would mean she is harming herself?
TL;DR: The Origin
header protects the innocent user. It does not secure resources on a server. It is spoofable by an attacker on his own machine, but it cannot be spoofed on a machine not under his control.
Servers should still protect their resources, as a matching Origin
header doesn't mean an authorized access. However, a Origin
header that does NOT match means an unauthorized access.