Understanding the Same-Origin Policy in Web Security
What is the Same-Origin Policy?
The Same-Origin Policy was introduced by Netscape in 1995 for web browsers. Initially, it meant that cookies set by webpage A could not be accessed by webpage B unless they were "same-origin."
Same-origin is defined as having the same protocol, domain, and port.
Purpose of the Same-Origin Policy
The goal of the Same-Origin Policy is to protect user information security by preventing malicious websites from stealing data.
Without this policy, the following scenario could occur:
- A user logs into website A (e.g., a bank or e-commerce site).
- The user then visits an attacker's website B, where scripts read cookies from website A.
- The attacker obtains cookies from website A; if these cookies contain private information (such as account balances), it could be leaked. More dangerously, cookies often store login states, allowing other sites to impersonate the user if they haven't logged out.
Thus, the Same-Origin Policy is essential; otherwise, cookies could be shared, making the internet unsafe.
Note that browsers also allow form submissions without Same-Origin Policy restrictions.
Evolution of the Same-Origin Policy
As the internet has developed, the Same-Origin Policy has become stricter. Currently, for non-same-origin requests, three behaviors are restricted:
- Cookies, LocalStorage, and IndexDB cannot be read (Cookies are small pieces of information written by servers to browsers, only shareable with same-origin pages. However, if two pages share the same top-level domain but differ in subdomain, browsers may allow cookie sharing via
document.domain. For example, inwww.example.com, the top-level domain isexample.com, and the subdomain iswww.example.com). - DOM cannot be accessed (also requires the same top-level domain).
- AJAX requests cannot be sent.
Need for Cross-Origin Communication
With the trend of separating front-end and back-end, pages on website A may need to access data from website B, requiring methods to bypass the Same-Origin Policy for cross-origin data exchange.
Cross-origin approaches include:
JSONP
JSONP leverages the fact that <script> tags can load JavaScript files from other domains. We can use this to fetch data from other domains.
For example, to query product information from a third-party e-commerce site, we can make a request via a script tag:
<script src="http://shop/getProductions?type=0&pageIndex=1&pageSize=10"></script>
The backend receives request, queries the product information, and returns the results in a JavaScript file to the frontend, such as:
onProductionsReceived([
{id:0, name:'Product1', price: 16},
{id:1, name:'Product2', price: 52},
{id:2, name:'Product3', price: 32},
]);
The browser executes this JavaScript file, calling the onProductionsReceived() function. Note that this function must be predefined on the frontend, for example:
function onProductionsReceived(products) {
console.log("Received product list", products);
}
CORS
CORS stands for Cross-Origin Resource Sharing, a method for AJAX cross-origin requests, supported by modern browsers and IE 10+.
The principle of CORS is:
- The browser detects that the request does not comply with the Same-Origin Policy and adds an
Originheader to the request. - The server receives it and adds an
Access-Control-Allow-Originheader to the response. - The browser checks if
Access-Control-Allow-Originincludes the specifiedOrigin; if yes, it processes the response, otherwise it rejects it.
Example server-side code:
res.setHeader('Access-Control-Allow-Origin','http://localhost:8080'); // Allow requests from http://localhost:8080
res.setHeader('Access-Control-Allow-Origin','*'); // Allow all requests
Note: The Same-Origin Policy does not restrict the sending or receiving of requests; it only prevents JavaScript from manipulating response resources.
Proxy
During front end development, we often need to access data from remote servers via AJAX in a development environment, leading to cross-origin issues and preventing normal data retrieval. Using CORS might not be appropriate if it requires server-side permission for domains like http://127.0.0.1:8080. In such cases, we can use a proxy to access cross-origin data.
The principle of a proxy is: the Same-Origin Policy only restricts browsers, not servers. Specifically:
- The browser sends a request to the development environment server.
- The development server forwards the request to the target remote server based on the URL, receives the data, and sends it back to the browser.
- The browser receives and displays the data.
Reference Materials
Information viewed but not recorded, deleted if infringing.