...

/

Cross-Origin Resource Sharing (CORS) in APIs

Cross-Origin Resource Sharing (CORS) in APIs

Learn how APIs interact with different domains using cross-origin resource sharing.

Background

With the introduction of JavaScript and Document Object Model (DOM) in web browsers, manipulating an HTML document's objects and properties using JavaScript became possible. As a result, a malicious script loaded by one web page could interact with the resources from another web page and retrieve sensitive information using the latter's DOM. This vulnerability of the DOM could be exploited by forgery attacks, such as a CSRF attackCross-site request forgery attack, where a malicious request is forged to make it look like it’s been made by a legitimate user. This is used to gain access to private data and perform malicious actions., through which attackers could gain unauthorized access to different resources. Here is an example scenario:

Suppose that John is lured into visiting www.evil-site.com. This site responds with JavaScript code that then makes a call to www.facebook.com, where John logs in without any hesitation. As a consequence, the JavaScript code downloaded from www.evil-site.com obtains access to the DOM elements of www.facebook.com and, by virtue, to John's sensitive data.

The origin problem

The example that we saw above demonstrates an unrestricted interaction between two web pages belonging to different origins, which could lead to a potential data breach. An origin is defined as a combination of scheme (protocol), hostname, and port number (if specified). Two URLs are said to have the same origin if and only if they have the same schemes, hostnames, and port numbers.

Press + to interact
An example of defining an origin
An example of defining an origin

URLs with different hostnames belong to different origins. A request that spans across different origins is known as a cross-origin request.

The following code compares the origins of two URLs. Try changing the URLs to see if they have the same origin.

Press + to interact
#default port for http is 80 and for https is 443
url1 = 'http://example.com'
url2 = 'http://example.com:80/index.html'

The same-origin policy (SOP)

To combat this susceptibility and reduce attack vectors, the engineers at Netscape defined a rule called the same-origin policy (SOP), whereby two web pages can only interact with each other if they belong to the same origin. Simply put, the URL www.evil-site.com can’t access the resources of www.facebook.com since they both have different origins.

The illustration below depicts a same-origin request, where the URL http://abc.com ...