In this section, we will take a look at the concept of CORS, which has a significant role to play in modern web applications.
CORS stands for Cross Origin Resource Sharing.
Before understanding CORS, let us take a look at Cross Origin Requests. In HTTP, a Cross Origin request happens when a resource, which belongs to a particular domain, makes a request to a resource which resides in another domain.
Historically, browser implementations were preventing the Cross Origin requests for security reasons. But with the recent advances in UI technology (and the way applications are built), Cross Origin requests look inevitable, and a new standard was required to allow Cross Origin requests.
W3C came up with a standard way of allowing Cross Origin requests, known as ‘Cross Origin Resource Sharing’.
Note that including image urls from a different domain in an html page doesn’t come under Cross Origin requests. Generally, Cross domain AJAX requests, HTTP request methods from libraries like Angular etc. come under Cross Origin requests.
How does CORS work?
As part of CORS specification, a few simple Cross origin requests are allowed by default. For e.g., GET, HEAD, POST requests (there are some MIME type constraints as well for these requests) are allowed based on the MIME types. For other type of requests, whenever cross origin request is made by a script, the browser has to send a pre-flight request to the corresponding server (i.e, to mycontacts.com server in above example).
A Preflight request is a HTTP OPTIONS request sent by the browser to the server, along with details like origin server (which is the original server url to which the resource belongs to), the type of HTTP request being attempted (i.e. GET/POST etc.), Content type etc.
While using libraries like Angular JS and making Cross Origin requests, if we inspect the Network calls made, we can see a lot of OPTIONS requests made to the server. These OPTIONS requests are the Preflight requests sent by the browser.
The server should respond with a 200 status response for this Preflight request (if the origin domain is allowed and secure) with additional headers in the response like Access-Control-*. (Access-Control-Allow-Origin, Access-Control-Allow-Methods etc.).
If the server responds with a 200 OK response, then the browser sends the real request to the server. The above diagram illustrates the flow explained here.
Note that to allow CORS, browsers need to fully support CORS standard and the server needs to support the CORS request.
Generally, on the server side, a HTTP request filter is required to allow the server to respond to the preflight OPTIONS request. As a good practice, the server can also whitelist the domains from where the Cross domain requests should be allowed instead of allowing a blanket entry for requests from all domains.
Application Architecture and CORS: