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
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.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.