Sweet Desk Layout

A little about CORS

A little info about Cross-Origin Resource Sharing

As I start with most of my posts, I have to explain one thing in order to explain the main topic. In this case that is security. So as you probably know, or at least I assume you know if you are reading this, is that a lot of things are hosted on the internet. Everything from webpages to fonts to images. Some of these things are native to the server that the site you are looking at is hosted. and some are not. The ones that aren’t, are being pulled from a different server. There are two ways to handle these requests, Same-Origin and Cross-Origin.

SAME-ORIGIN POLICY

So everything in the same-origin policy, as the name might reveal, comes from the same origin, or in this case the same server. This is a very restrive way of handling data, but it helps mitigate attacks, by limiting attack vectors. There are three parts of an origin that have to match for same-origin, to allow sites to connect with each other protocol, host, and port number. If everything doesn't match, then access is restricted. The need for security is pretty obvious, but the same-origin policy is very restrictive.

CORS-CROSS-ORIGIN RESOURCE POLICY

That's where CORS comes in. It allows you to set what resources your site can access, things like stylesheets, fonts, or images. Browers for the purpose of security restrict cross-origin HTTP requests that were initiated from scripts. That means that XML requests and Fetch API follow the same-origin policy. The only way around that is if the other origins have the correct CORS headers, which I will get to shortly.

This is necessary because it allows sites to set who and how their assets can be accessed. Requests are made with traditional methods. Most sites will allow GET requests but probably won’t allow PATCH, PUT, or DELETE. CORS has its own list of headers that can be added to a request. They are:

Instead of just blindly blocking some requests, a pre-flight request is initiated. These requests will trigger a pre-flight:

  • PUT
  • DELETE
  • CONNECT
  • OPTIONS
  • TRACE
  • PATCH

The purpose of the pre-flight is to check whether say a DELETE request is safe to process. If it is the request will go through, if not it will block the request.

CONCLUSION

Now there you have it. I hope this gave you a slightly better understanding of what CORS is and how sites protect themselves. Look into the resources and increase your knowledge a little more.

RESOURCES

Full Stack Developer Ruby and Javascript. Recent grad of the Flatiron School.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store