Cross-Origin Resource Sharing (CORS)
Two Main Components
- Security and the Same-Origin Policy
(This is a policy that says that a web browser allows scripts in one page to access data in another page but only if they have the same origin. This policy protect us from rogue Javascript that will try to alter our data from another website.) - Block requests from rogue JavaScript
The same-origin policy is a concept of web security that allows scripts in Webpage 1 to access data from Webpage 2 only if they share the same domain. This means that the errors will be raised in the following cases:
- Different domains
- Different subdomains (
example.com
andapi.example.com
) - Different ports (
example.com
andexample.com:1234
) - Different protocols (
http://example.com
andhttps://example.com
)
The CORS is behaving exactly as it should. This policy is there to protect you and your users. For instance, attackers may embed malicious scripts in advertisements. This policy prevents those scripts from successfully making requests to your bank’s website as you access the website hosting the advertisement.
If you’re sending any requests beyond very simple GET or POST requests, then before your actual request is sent, the browser sends a preflight OPTIONS request to the server. If CORS is not enabled, then the browser will not respond properly and the actual request will not be sent.
CORS Headers
How does CORS handle that options preflight request?
Answer: It does so using HTTP response headers. It sets certain headers on the response to basically inform the client that you have passed and you may proceed.
In order for the requests to be processed properly, CORS utilizes headers to specify what the server will allow:
Header | Description |
---|---|
Access-Control-Allow-Origin | What client domains can access its resources. For any domain use * |
Access-Control-Allow-Credentials | Only if using cookies for authentication - in which case its value must be true |
Access-Control-Allow-Methods | List of HTTP request types allowed |
Access-Control-Allow-Headers | List of HTTP request header values the server will allow, particularly useful if you use any custom headers |