# CORS

## What is CORS

Cross-origin resource sharing.

CORS is not a security measure. It's a way to circumvent the "Same Origin Policy" which is the security measure preventing you from making ajax requests to a different domain.

Same Origin Policy - a website on one domain cannot make an xhr request to another domain. This policy is **implemented by the browser**. **It does not prevent an atacker from making requests to your server.**

CORS is a way to bypass SOP in some case where you want to allow one specific website to make requests to your server.

## How CORS work

CORS, like the rest of HTTP is basically a dialogue between the browser and the server.

Assuming your front-end is on domain-a.com and your API on Domain-b.com, it would go something like this :

&#x20; -**Browser :** "Hey Domain-B, this script on Domain-A.com is asking me to make an ajax query to you, but I'm supposed to block it unless you tell me it's OK."\
&#x20; -**Server :** "I don't know, but I can tell you that only `https://domain-a.com` is allowed to make GET, POST, OPTIONS and DELETE requests, and this needs to be validated every 10 minutes.\
&#x20; *Browser thinks to himself "yeah, that's the right domain, I'll send the request !"*\
&#x20; -**Browser :** "Hey domain-b, I'd like to POST on this endpoint please.\
&#x20; -**Server :** Sure thing, here's a 200

Or if the user is on a different domain the dialogue would be shorter, and look like that :

&#x20; -**Browser :** "Hey domain-b.com, this script on malicious-domain.com is asking me to make an ajax query to you, but I'm supposed to block it unless you tell me it's OK."\
&#x20; -**Server :** "I don't know, but I can tell you that only `https://domain-a.com` is allowed to make GET, POST, OPTIONS and DELETE requests, and this needs to be validated every 10 minutes.\
&#x20; *Browser thinks to himself "Oh it's not the right domain, we'd better not make that request" and proceeds to send an error in the console.*

More about it:&#x20;

* <https://dev.to/nicolus/what-you-should-know-about-cors-48d6>
* <https://dev.to/g33konaut/understanding-cors-aaf>
