The same-origin policy is a critical security technique that limits how a document or script loaded from one origin interacts with a resource from another.
It aids in the isolation of potentially harmful documents, hence minimising attack vectors. For example, it prevents a malicious website on the Internet from running JavaScript in a browser to read data from a third-party webmail service (to which the user is logged in) or a company intranet (which is protected from direct access by the attacker due to the lack of a public IP address) and relay that data to the attacker.
Definition of an origin
If the protocol, host, and port (if any) are the same for both URLs, then they share the same origin. The "scheme/host/port tuple" or simply "tuple" may be used to refer to this. (A "tuple" is a general form of double, triple, quadruple, quintuple, etc.; it is a group of objects that collectively create a whole.)
The following table gives examples of origin comparisons with the URL http://www.debug.school/map/blog.html:
URL | Outcome | Reason |
---|---|---|
http://www.debug.school/map2/page.html | Same origin | Only the path differs |
http://www.debug.school/map/inner/article.html | Same origin | Only the path differs |
https://www.debug.school/blog.html | Failure | Different protocol |
http://www.debug.school:81/map/blog.html | Failure | Different port (http:// is port 80 by default) |
http://article.debug.school/map/blog.html | Failure | Different host |
Inherited origins
Scripts executed from pages with an about:blank or javascript: URL inherit the origin of the document containing that URL, since these types of URLs do not contain information about an origin server.
For example, about:blank is often used as a URL of new, empty popup windows into which the parent script writes content. If this popup also contains JavaScript, that script would inherit the same origin as the script that created it.
data: URLs get a new, empty, security context.
File origins
Modern browsers usually treat the origin of files loaded using the file:/// schema as opaque origins. What this means is that if a file includes other files from the same folder (say), they are not assumed to come from the same origin, and may trigger CORS errors.
Note that the URL specification states that the origin of files is implementation-dependent, and some browsers may treat files in the same directory or subdirectory as same-origin even though this has security implications.
Cross-origin network access
The same-origin policy controls interactions between two different origins, such as when you use fetch() or an element. These interactions are typically placed into three categories:
The Same-Origin Policy (SOP) is a critical security concept implemented in web browsers to protect users from malicious websites trying to access sensitive data from other sites. Here's a breakdown of what it is and why it matters:
What is the Same-Origin Policy?
The Same-Origin Policy restricts how documents or scripts loaded from one origin can interact with resources from another origin.
An origin is defined by the combination of:
-
Protocol (e.g.,
http
,https
) -
Host (e.g.,
example.com
) -
Port (e.g.,
:80
,:443
)
So, for example:
-
https://example.com
andhttp://example.com
are different origins (different protocol). -
https://example.com
andhttps://api.example.com
are different origins (different subdomain). -
https://example.com:443
andhttps://example.com:8443
are different origins (different port).
What Does SOP Restrict?
Under SOP, a script from one origin cannot:
- Read data from another origin’s DOM.
- Make AJAX requests to another origin (unless CORS is enabled).
- Access cookies, local storage, or session storage from another origin.
What Can Bypass SOP?
There are controlled ways to allow cross-origin communication:
- CORS (Cross-Origin Resource Sharing): A server can explicitly allow requests from other origins using HTTP headers.
-
JSONP (deprecated): A workaround for cross-origin GET requests using
<script>
tags. - PostMessage API: Allows safe cross-origin communication between windows or iframes.
- Proxying requests through the same origin: Using a backend server to fetch data from another origin.
️ Why is SOP Important?
It prevents Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF) attacks by ensuring that malicious scripts from one site can't steal data from another site the user is logged into.
Examples
Frontend (JavaScript in Browser)
<!DOCTYPE html>
<html>
<head>
<title>CORS Example</title>
</head>
<body>
<button onclick="makeRequest()">Fetch Data</button>
<pre id="output"></pre>
<script>
function makeRequest() {
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
// credentials: 'include' // use this if cookies/auth are involved
})
.then(response => {
if (!response.ok) throw new Error('Network response was not ok');
return response.json();
})
.then(data => {
document.getElementById('output').textContent = JSON.stringify(data, null, 2);
})
.catch(error => {
console.error('Fetch error:', error);
});
}
</script>
</body>
</html>
Backend (Node.js/Express Example with CORS Enabled)
const express = require('express');
const cors = require('cors');
const app = express();
// Enable CORS for all origins (you can restrict this)
app.use(cors());
app.get('/data', (req, res) => {
res.json({ message: 'Hello from the API!' });
});
app.listen(3000, () => {
console.log('API server running on http://localhost:3000');
});
How it works
The browser tries to fetch data from https://api.example.com/data.
The server must include the header:
Access-Control-Allow-Origin: *
or a specific origin like https://yourfrontend.com to allow the request.
If CORS is not enabled on the server, the browser will block the request due to the Same-Origin Policy.
Ref: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
Top comments (0)