DEV Community

Nicolas Bailly
Nicolas Bailly

Posted on • Updated on

What you should know about CORS

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 those darn ajax requests and be done with it. So you went to stack overflow, copy pasted a code snippet to set some headers, and it worked.

There are however a few things you might want to know.

What CORS is, and what it is not

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.

The Same Origin Policy states that a website on one domain cannot make an xhr request to another domain. This prevents a malicious website from making requests to a known website (think Facebook or Google) hoping the user are already logged-in so that it can impersonate them.
This policy is implemented by the browser (all of them implement SOP, although there are minor differences), which means that it won't apply to requests made from a server, or any other HTTP clients like cURL or POSTman. Also the server has absolutely no control over this : it will process every request as if it was coming from a trusted domain, it is entirely up to the browser to block the requests.

SOP is in no way meant to prevent an attacker from making requests to your server (since an attacker would obviously not use a browser). It's only meant to prevent legitimate users using a reputable browser from unknowingly making requests to your website.

Now CORS are a way to bypass SOP in some cases where you want to allow one specific website to make requests to your server, even though it would normally be blocked. (typically, to allow your front-end app to make requests to your API).

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 :

  -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."
  -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.
  Browser thinks to himself "yeah, that's the right domain, I'll send the request !"
  -Browser : "Hey domain-b, I'd like to POST on this endpoint please.
  -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 :

  -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."
  -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.
  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.

How it looks in the browser

In my little scenes above, the first question from the browser is called a Preflight request, and the corresponding HTTP verb is OPTIONS. The server should always answer to Preflight Requests with a 200 response that has no body but contains the Access-Control-Allow-Origin and a few other headers. In our example the headers would be :

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://domain-a.com
Access-Control-Allow-Methods: GET, POST, OPTIONS, DELETE
Access-Control-Max-Age: 3600
Enter fullscreen mode Exit fullscreen mode

It tells the browser that it can only perform the request if it comes from domain-A.com, that it can only make GET, POST, OPTIONS or DELETE requests (a PUT request would be blocked for example), and that it can cache this information for 3600 seconds so it doesn't need to make a new OPTIONS request every single time.

And of course, if we're on a different domain that won't work. The browser will send an OPTIONS request, throw an error in the console and never send the POST request :

Pretty straight forward, right ?

Well yes, except there are a few gotchas...

Tricky things about CORS

All Responses should contain the CORS headers

You might think that if your server answers to the OPTIONS request with a 200 and the right headers you're in the clear, and you'll see the browser send the OPTIONS request, then send your actual request, and then fail miserably... That's because every request (GET, POST, or otherwise) should also contain the same "Access-Control-Allow-Headers".

Not all requests will trigger a Preflight Request

There are a few requests that won't trigger a Preflight Request, for example GET requests, or POST request with with a Content-Type header set to application/x-www-form-urlencoded. Those are "simple requests" that have always been allowed by browsers (you've always been able to make a link or POST a form to a different website, even before CORS exsisted), and you can find the full list here.
in the case of a POST request the result is a little counter-intuitive : The browser will make the POST Request (so your server will likely persist some data), and then ignore the response !

In a traditional web app you'd use application/json as a content-type so there will be a preflight request, but keep in mind your server may still receive POST requests from other domains, so don't blindly accept them.

The allowed domain must include the protocol

You can't just put mydomain.com as a domain, it needs to include the protocol (eg. https://mydomain.com). The fun part is you can't really accept both http and https because...

You can only allow one domain

You can either allow every domain with Access-Control-Allow-Origin: *, or only one. This means that if you need several domains to access your api, you'll need to handle it yourself.

The easiest way to handle this is to maintain a list of allowed domains on your server, and change the content of the header dynamically if the domain is in that list. Here's how it would look in plain PHP for example :

$allowedDomains = [
    "http://www.mydomain.com",
    "https://www.mydomain.com",
    "http://www.myotherdomain.com",
    "http://www.myotherdomain.com",
];

$originDomain = $_SERVER['HTTP_ORIGIN'];

if (in_array($originDomain, $allowedDomains)) {
    header("Access-Control-Allow-Origin: $originDomain");
};
Enter fullscreen mode Exit fullscreen mode

Or in Node.js (adapted from this SO anwser)

app.use(function(req, res, next) {
  const allowedOrigins = [
    "http://www.mydomain.com",
    "https://www.mydomain.com",
    "http://www.myotherdomain.com",
    "http://www.myotherdomain.com",
  ];
  const origin = req.headers.origin;
  if(allowedOrigins.indexOf(origin) > -1){
    res.setHeader('Access-Control-Allow-Origin', origin);
  }
  return next();
});
Enter fullscreen mode Exit fullscreen mode

Same Origin Policy applies to the file system on Chrome and Safari, not on Firefox.

If you make a request to a local file, Firefox will consider that it's always on the same domain and allow the request. Webkit based browsers like Chrome or Safari will consider this a security risk and block ajax queries to local files. 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.
As pointed out by @brianjenkins94 in the comments, you could also start Chrome with the --disable-web-security flag.

The iOS WKWebview needs CORS

If you're developing a mobile app that uses a webview (with Cordova or Ionic), Android won't give you any trouble, but the new WKWebview on iOS will require CORS. This means you pretty much have to always set the Access-Control-Allow-Origin header to *, which is really not ideal.
Another alternative is to not make ajax requests in your app and use a cordova plugin to make native http requests, which will happily ignore the Same origin Policy.

Thanks for reading !
If you want a more in depth description of CORS, head to MDN : https://developer.mozilla.org/docs/Web/HTTP/CORS.

Oldest comments (32)

Collapse
 
wattafot profile image
wattafot

Thanks for sharing!

Collapse
 
alex_escalante profile image
Alex Escalante

This is a good article!

Collapse
 
brujua profile image
Bruno Crisafulli

Very good article: informative and comprehensive. Thanks!

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
Nicolas Bailly

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
 
maurycyszmurlo profile image
Maurycy Szmurlo

Very clear.
Thanks for sharing

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
 
danjconn profile image
Dan Conn

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

Collapse
 
marekf profile image
Scrascom laptopy poleasingowe Wrocław

Thank you for sharing!

Collapse
 
haripraghashs profile image
Hari subramaniam

Excellent article. Extremely clear and well articulated

Collapse
 
shayd16 profile image
Shayne Darren

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

Collapse
 
alexandcote profile image
Alexandre Côté

Nice article 👏🏻

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...

Some comments may only be visible to logged-in visitors. Sign in to view all comments.