DEV Community

What you should know about CORS

Nicolus on July 14, 2019

If you're anything like me, the first time you encountered CORS (or Cross-origin resource sharing), all you wanted was for your server to accept th...
Collapse
 
brianjenkins94 profile image
Brian Jenkins

The only way to get around this is to either use Firefox, or install a web server that will send an Access-Control-Allow-Origin: * header.

You can also run Chrome with --disable-web-security:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir=C:\HighwayToTheDangerChrome
Collapse
 
nicolus profile image
Nicolus

Thanks ! I added that tip to the main article.

Collapse
 
widygui93 profile image
Widy Guilias

Hi, Brian.

I'm wondering is it okay to disable web security?

Collapse
 
brianjenkins94 profile image
Brian Jenkins

Not for general browsing, but for circumventing CORS it's fine.

Collapse
 
jokingzhang profile image
zhangboxuan

Hey man! This article is awesome, I am currently learning CORS, Can I translate your article, learn, and then put it on the China Programming Forum website like Stack Overflow? Website Addr: segmentfault.com/ . And I will attach the original article link.

Collapse
 
nicolus profile image
Nicolus

Sure, as long as you include the original link it's not a problem. Thank you !

Collapse
 
chrisfosterelli profile image
Chris Foster

Awesome post Nicolas! I really like your description of how the whole process works. I wanted to share a thought on this piece here you might find interesting:

This is often a source of confusion for newcomers because it's not immediately apparent what CORS is supposed achieve. Firstly CORS is not a security measure in itself, it's actually the opposite: CORS is a way to circumvent the "Same Origin Policy" which is the security measure preventing you from making ajax requests to a different domain.

I agree this is true for the CORS headers, but I think CORS itself means something more general. There is a lot of terminology confusion here community-wide, so I try to go by the spec. Formally any request with an Origin header is a "CORS Request", regardless of what headers are present on the response. The CORS Protocol specification applies to CORS Requests and outlines both when and when not to allow CORS Requests to take place.

AFAIK there is no formal specification for the "same-origin policy", but different specs outline various cross-origin limitations (including those from the CORS Protocol) which is the term the browser error kind of lumps them together under.

Based on that I believe it is technically correct to say that the CORS Protocol is a security measure in itself. However the headers component of the CORS Protocol is definitely a way to circumvent the same-origin policy which I think might have been aligned with what you had in mind for that paragraph.

Thanks again for sharing!

Collapse
 
nicolus profile image
Nicolus • Edited

Hey, thanks for your input !

You're probably right about that in the sense that SOP isn't a specification while CORS is, and the spec expects browsers to block cross origin requests by default.

However, the introduction to the spec says

User agents commonly apply same-origin restrictions to network requests. These restrictions prevent a client-side Web application running from one origin from obtaining data retrieved from another origin [...]
This specification extends this model in several ways

The way I interpret this is that historically browsers started to implement "Same Origin Policies" before CORS, and CORS was created primarily to allow requests that would never have been possible otherwise.

So while you're technically correct, I think I'll leave my imprecise wording because it personally helped me deal with CORS when I stopped thinking about it as "this thing that prevents me from querying my API" and started thinking of it as "this clever system that allows me to query my API even if it's on a different domain".

Collapse
 
batmanlover667 profile image
batmanlover667

hi Nicolas,

Great article, you almost saved my life :P

I have one doubt, if the request origin header is is not matching to Allow-Origin-Request-Header value , why it is giving 200 ok as an respose. It shall give 401 if the both side thing is not matching .

Request origin: Evil.com

Response header :
200 ok
Allow-origin-access-control: legitimate .com

why 200 ok, why not 401 ??

Collapse
 
nicolus profile image
Nicolus

Because CORS is handled by the browser. The server will never block any requests because of CORS. It's not its responsibility.

The server will always answer with a 200, but add some headers telling the browser "you're only allowed to accept this if the request was done from this domain", and the browser will block the request (and add a lovely warning in the console) if it doesn't match.

Once again, CORS is not meant to prevent malicious user agents from accessing a resource, it's only meant to prevent trusted user agents (browsers) from being tricked into impersonating the user by malicious websites. This means that asking the server to do the check and respond with a 403 would not be more effective, and since you can't expect every backend developer to implement the check correctly you'd still need the browser to check 200 responses and block them if needed.

Hope that helps !

Collapse
 
batmanlover667 profile image
batmanlover667

Thanks Nicolas for the quick reply, in my case if the response is giving a lot of data than possibility of CSRF is there.

Speaking with server , browser is not only one way to communicate , if i send the request from a server to server with changed origin , if it gives data back to as an response than CSRF can be done. ..Right ??

Correct me if i am wrong .

Collapse
 
vagoel profile image
Varun

Thanks Nicolas for peeling out all the complexity around CORS and making it super easy to understand.
One can always refer to MDN docs for advanced CORS concepts but your simplified definitions is very helpful for a lot like me.

Collapse
 
alex_escalante profile image
Alex Escalante

This is a good article!

Collapse
 
wattafot profile image
wattafot

Thanks for sharing!

Collapse
 
mollynem profile image
Molly Nemerever

great info! I liked the conversations between the browser and server 🤓

Collapse
 
sakar_dhana profile image
Sakar

Very Well written article on CORS. Must read for all beginners. Thanks, keep the good work going...

Collapse
 
maurycyszmurlo profile image
Maurycy Szmurlo

Very clear.
Thanks for sharing

Collapse
 
brujua profile image
Bruno Crisafulli

Very good article: informative and comprehensive. Thanks!

Collapse
 
bc7 profile image
Brian

This is great Nicolas, thanks for sharing! I'm definitely passing this to my students who run into this issue often.

Collapse
 
devjesusarc profile image
Jesus Arciniega

Excellent info!!

Collapse
 
tuchedsf profile image
Diego

Thanks. Nice article...

Collapse
 
bradleycollins profile image
Bradley Collins

I run into this a lot when dealing with development environments (as a PM), super good read and helped me understand it a bit more!

Collapse
 
marekf profile image
Scrascom laptopy poleasingowe Wrocław

Thank you for sharing!

Collapse
 
dimitropoulos profile image
Dimitri Mitropoulos • Edited

typo:

    "http://www.myotherdomain.com",
    "http://www.myotherdomain.com",

you meant to make the second one https in both the php and node example

Collapse
 
danjconn profile image
Dan Conn

A really good write-up of a much misunderstood problem! Thanks!

Collapse
 
haripraghashs profile image
Hari subramaniam

Excellent article. Extremely clear and well articulated

Collapse
 
_smellycode profile image
нιтєѕн кυмαя

Good, write up Nicolas. Last month, I tried to explain the same with the help of a sample TODO application. You might like it smellycode.com/csrf-in-action/

Collapse
 
alexandcote profile image
Alexandre Côté

Nice article 👏🏻

Collapse
 
shayd16 profile image
Shayne Darren

Great article, could you also add the bit about how subdomains work as well, please.

Collapse
 
ericomartin profile image
EricoMartin

Thank you. This was very helpful.