DEV Community

Discussion on: CORS, In A Way I Can Understand

Collapse
 
grimlck profile image
Michael

Hey Doug,

since CORS was bothering me too lately I fully understand your pain :) and I'd like to try to shed some light. Unfortinately the metaphor you came up with doesn't explain the concept behind CORS. But first things first, browsers implement something called "Same-origin Policy" (SOP) (en.wikipedia.org/wiki/Same-origin_...) that says, two websites can load each others contents only if they are both from the same origin where an origin is composed of the scheme the host name and the port - like "example.org:443" (when using standard ports those can be omitted). If the origins of the two sites differ, loading content from each other is not permitted, unless we use CORS to poke little holes into the SOP (even bigger holes when you are not careful enough).

Furthermore CORS response headers are only set on the remote resources, that means you are not able to permit or deny the loading of external content with them on your end. This could be achieved with the use of a "Content Security Policy" (this is what you describe in your ad example and this is where your metaphor applies).

Now for CORS the easiest example is the scenario where you would include a web font, hosted on one of those font sites (Site B), on your website (Site A). Because web fonts are subject to CORS the provider has to make sure that browsers are able to call the resource by adding the header "Access-Control-Allow-Origin" normally with an asterisk (*) as value because the provider doesn't know which origins stop by. A browser would load Site A - detects it should load a font from Site B (another origin) - sends a CORS request to get the resource - finds a valid CORS response header - displays the font.

And finally we get back to your metaphor where we have to shift the perspective a bit. You would tell your child to give away your car key when you are away but you do not tell her to whom. Then a stranger couldn't even knock on your door (because of that annoying error message :D). You could also tell her, give the key only to your grandma. The situation for a stranger wouldn't change, still not able to knock. But when her grandma stands at the door and requests the key your daughter would give it to her. The last possibility is, you think "what the heck", you can give the key to anyone who knocks. A stranger comes by, knocks, requests the key and has a nice ride in your car.

I hope this helps to understand CORS a little bit better.

Further reading:

Some advice at the end:

  • be careful when designing CORS rules
  • use wildcards in "Access-Control-Allow-Origin" only if it is a public resource
  • be cautious with CORS headers when using intermediate caches
Collapse
 
dougblackjr profile image
Doug Black

This is fantastic, thank you!