One of the first terms that brings up in the development of rich internet applications (RIA) is the term Cross-Origin Resource Sharing (CORS).
The goal of this protocol, conceived at the beginning of 2014, is to allow the access to resources allocated in a specific domain troughout requests sent from any other different domain.
Fine, but, what is the real meaning of this? Let’s start from the beginning …
Before the appearance of the CORS protocol, if we wanted to, for example, send an AJAX request to a specific URL, the browsers of that time (IE < 8.0, Firefox < 3.5, Chrome < 3) only allowed requests sent from the same domain.
No only that, but also requests with the following characteristics would have been rejected:
Until CORS birth, there were some ways to pseudo-avoid this limitations, like using JSOPN, but they were not standard, not generic solutions which could be applied in every situation.
DEFINING A CORS POLICY
However, now we can set a CORS policy to handle this situations. The question is: how can we do that?.
In the following way:
When a current browser detects a possible CORS request, the first thing it will do is keeping this request awaiting while it send its own http request with the OPTIONS method. At first sight this may seems confusing, due to all this process is handled entirely by the browser, so if you are not used to it, you may get lost in this flow. But actually, this is a very basic flow once you get to understand it.
As it have been said, the first thing that the server will receive is an OPTIONS request. If this request is not handled, the browser will block the current request and the execution will be finished, as it happened in the previous times.
To allow cross domain access, it is necessary to catch this OPTIONS request in the server, as it would be done with any other http request, and return a response with the following header:
With this header, every request sent from the www.mydomain.com domain will be allowed. The browser will validate this response, and if the request has indeed been sent from this domain, it will allow the access to the original request, enabling this way interactive access to resources of different domains.
In case it would be needed to allow access to every request sent from any domain, the header returned must be the following:
Despite of all the potential offered by the CORS protocol, there is a hidden risk. And it is that we cannot afford to start allowing indiscriminate access to our resources from external domains or we may be generating huge security holes.
So it is necessary to decide carefully which ones are the allowed domains, and allowing access to every domain (‘*’), is usually a not recommended practice at all.
Are you ready for using CORS is your apps?