Cross-Origin Resource Sharing (CORS) in APIs
Explore Cross-Origin Resource Sharing (CORS) in APIs to understand how web browsers manage cross-origin requests and protect against security risks. Learn the differences between simple and preflight requests, how authentication integrates with CORS, common vulnerabilities, and best practices to securely implement CORS in API design.
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.
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 ...