Sunday, October 08, 2017

Ruminating on CORS in REST APIs

Of all the articles I have studied on CORS, the below article by Derric Gilling is the most awesome. It is highly recommended to peruse this article to understand the fundamentals of CORS and how to enable REST APIs to support this.

https://www.moesif.com/blog/technical/cors/Authoritative-Guide-to-CORS-Cross-Origin-Resource-Sharing-for-REST-APIs/

Jotting down snippets from the above article:

-------------------------------------------------------
CORS is a security mechanism that allows a web page from one domain or Origin to access a resource with a different domain (a cross-domain request). CORS is a relaxation of the same-origin policy implemented in modern browsers. Without features like CORS, websites are restricted to accessing resources from the same origin through what is known as same-origin policy.

The cross-domain vulnerability existed earlier because a hacker website could make authenticated malicious AJAX calls to https://examplebank.com/api to POST /withdraw even though the hacker website doesn’t have direct access to the bank’s cookiesThis is due to the browser behavior of automatically attaching any cookies bounded to https://examplebank.com for any HTTP calls to that domain, including AJAX calls from https://evilunicorns.com to https://examplebank.com.

Why was CORS created?

There are legitimate reasons for a website to make cross-origin HTTP requests. Maybe a single-page app at https://mydomain.com needs to make AJAX calls to https://api.mydomain.com; or maybe https://mydomain.com incorporates some 3rd party fonts or analytics providers like Google Analytics or MixPanel. Cross-Origin Resource Sharing (CORS) enables these cross-domain requests. 

The CORS standard specifies the handshake between the browser and the server. The server has control over whether to allow the request or not depending on the origin of the request (Origin Header). The browser guarantees that the Origin request header is set reliably and accurately. Hence the server can restrict access to only selected URLs. 
-------------------------------------------------------

Implementing CORS in Spring Boot is very easy. The following article shows the various options available in a Spring MVC REST service to enable CORS - http://www.baeldung.com/spring-cors