Why the same-origin policy is the foundation of browser security
When you open your bank in one tab and a random blog in another, nothing stops the blog's JavaScript from sending requests to your bank. Your browser will even attach your bank cookies to them. What stops the blog from reading the answers (your balance, your messages) is the same-origin policy (SOP).
SOP is the single most important security mechanism in the browser. Nearly every client-side vulnerability class is understood in relation to it:
- XSS is dangerous because injected script runs inside the victim origin, where SOP is on its side.
- CSRF exists because SOP does not stop sending cross-origin requests, only reading the response.
- CORS misconfigurations are mistakes in deliberately relaxing SOP.
- Clickjacking, postMessage bugs, JSONP, DOM clobbering, cross-site leaks all live at SOP's edges.
If you can state exactly what SOP prevents and what it permits, you can quickly decide whether a bug is real and how far it goes.
What is an origin?
An origin is the triple scheme + host + port. Two URLs are same-origin only if all three match exactly.
Using https://app.example.com/page (default port 443) as the reference:
| Compared URL | Same origin? | Why |
|---|---|---|
https://app.example.com/other/path?x=1 |
Yes | Path and query do not matter |
http://app.example.com/page |
No | Different scheme |
https://app.example.com:8443/page |
No | Different port |
https://api.example.com/page |
No | Different host (subdomain) |
https://example.com/page |
No | Different host |
https://app.example.com:443/page |
Yes | 443 is the default for https |
https://app.example.com.evil.com/ |
No | Different host entirely |
You can print your current origin in the DevTools Console: location.origin. Some contexts have an opaque origin (sandboxed iframes, data: URLs) that matches nothing, including itself in some comparisons, and rendered as the string null. Remember null as an origin: it will matter in CORS bugs.
Same-site versus same-origin
Two related but different concepts frequently confused, and the difference is critical for cookies and CSRF.
A site is the scheme plus the registrable domain, also called eTLD+1 (effective top-level domain plus one label). The "effective TLD" comes from the Public Suffix List, a community list of suffixes under which anyone can register names: com, org, co.uk, github.io, herokuapp.com, blogspot.com.
| URL | eTLD | eTLD+1 (registrable domain) |
|---|---|---|
https://app.example.com |
com |
example.com |
https://www.example.co.uk |
co.uk |
example.co.uk |
https://alice.github.io |
github.io |
alice.github.io |
Because github.io is a public suffix, alice.github.io and bob.github.io are different sites, even though they share a parent. Without that list, all GitHub Pages sites would be "same-site" and could abuse each other's cookies.
Comparison:
| Pair | Same-origin | Same-site |
|---|---|---|
https://a.example.com vs https://a.example.com/x |
Yes | Yes |
https://a.example.com vs https://b.example.com |
No | Yes |
https://example.com vs https://example.com:8443 |
No | Yes (port ignored by "site" in the schemeful definition used today) |
http://example.com vs https://example.com |
No | No with schemeful same-site (modern browsers), yes in the older host-only definition |
https://a.example.com vs https://a.other.com |
No | No |
Why it matters:
- Same-origin is the unit of SOP: it governs what scripts may read.
- Same-site is the unit of
SameSitecookies and of other defenses such as Fetch Metadata (Sec-Fetch-Site: same-site | same-origin | cross-site | none). - A request from
blog.example.comtoapp.example.comis cross-origin (SOP applies, CORS needed to read) but same-site (SameSite cookies are sent). Consequently an XSS or a takeover on any sibling subdomain is much more dangerous than it looks: it is same-site for cookie purposes and can often set cookies for the parent domain. - "Cross-site" means "not same-site". "Cross-origin" is broader: every cross-site request is cross-origin, but not the reverse.
What SOP actually restricts
SOP is about reading and interacting, not about sending. Cross-origin embedding and sending are generally permitted; cross-origin reading is not.
Typically allowed (cross-origin)
- Embedding resources:
<img>,<script src>,<link rel=stylesheet>,<video>,<audio>,<iframe>(subject to framing headers), fonts (with CORS),<form>targets. - Sending requests: links, form submissions (including
POST),fetch/XHR "simple" requests (they are sent, though the page may not read the response). - Navigation:
window.location = "https://other.com".
Typically blocked (cross-origin)
- Reading the response of a
fetch/XMLHttpRequestto another origin (unless CORS allows it). - Reading the DOM of a framed or opened window from another origin (
iframe.contentDocumentthrows). - Reading storage:
localStorage,sessionStorage,IndexedDBand non-shared cookies are per-origin (cookies are scoped by domain and path, not by origin, with their own rules). - Reading pixels of a cross-origin image drawn on a
<canvas>(the canvas becomes "tainted").
Limited cross-origin interactions that remain
window.postMessagelets windows from different origins talk by agreement. The receiver must checkevent.origin. Missing checks are a classic bug.- A few properties of
window.locationcan be written cross-origin (navigation), andwindow.frames.length/window.closedcan be read. <script src>from another origin executes in your origin with your privileges. That is how JSONP and CDN-hosted libraries work and why a compromised third-party script is a full compromise.
The "send but cannot read" consequence
An attacker page can do this against your bank while you are logged in:
<form action="https://bank.example/transfer" method="POST">
<input name="to" value="attacker">
<input name="amount" value="1000">
</form>
<script>document.forms[0].submit()</script>
SOP does not block the request. The browser sends it with whatever cookies SameSite allows. The attacker cannot read the response, but the state change already happened. That is CSRF, and it is the reason SOP alone is not enough protection for state-changing actions.
Cross-origin resource sharing (CORS)
SOP is sometimes too strict. A single-page app at https://app.example.com legitimately needs to call an API at https://api.example.com. CORS is the mechanism for a server to opt in to being read by specific other origins using HTTP headers. CORS relaxes SOP; it does not tighten it.
Simple flow
- The page at
https://app.example.comrunsfetch("https://api.example.com/me"). - The browser adds
Origin: https://app.example.comto the request. - The API replies with a header naming who may read it:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://app.example.com
Content-Type: application/json
{"user":"alice"}
- The browser compares. If the allowed origin matches (or is
*), JavaScript may read the response. If not, the request may still have been sent and processed, but the script gets an error.
Preflight
For "non-simple" requests (methods other than GET/HEAD/POST, custom headers, or content types other than form/text), the browser first sends an OPTIONS preflight:
OPTIONS /me HTTP/1.1
Origin: https://app.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: content-type, x-api-key
The server answers with Access-Control-Allow-Methods, Access-Control-Allow-Headers and Access-Control-Max-Age. Only if approved is the real request sent. A "simple" cross-origin POST with Content-Type: application/x-www-form-urlencoded needs no preflight, which is why CSRF-style attacks still work.
Credentials
By default cross-origin fetch does not send cookies. The page must opt in (credentials: "include"), and the server must reply with Access-Control-Allow-Credentials: true and a specific origin, since * is forbidden together with credentials.
CORS misconfigurations (what hackers look for)
| Misconfiguration | Impact |
|---|---|
Server reflects any Origin into Access-Control-Allow-Origin and sets Allow-Credentials: true |
Any website can read authenticated responses: data theft |
Allow-list by regex or startsWith/endsWith (e.g. accepts https://app.example.com.evil.com or https://evilapp.example.com) |
Same as above via a lookalike origin |
Trusting the null origin |
Attackers can send Origin: null from a sandboxed iframe or data: URL |
| Trusting all subdomains | XSS or takeover on any subdomain becomes API access |
Access-Control-Allow-Origin: * on endpoints returning private data keyed by network position (intranet) |
Internal data exposed to external sites |
Missing Vary: Origin while reflecting Origin |
Cache poisoning of CORS headers |
Important nuance: Access-Control-Allow-Origin: * without credentials is not automatically a vulnerability; it matters only if the response contains data that should be private. The dangerous combination is a reflected/trusted origin plus credentials, or private data reachable without credentials.
How SOP relaxes and bypasses
Know these so you recognize them in applications:
document.domain: legacy way for two subdomains to both setdocument.domain = "example.com"and become same-origin. Deprecated and being removed; any subdomain compromise is effectively full compromise.- JSONP: wrapping data in a function call loaded with
<script src>. It bypasses SOP by design and can leak data to any origin that includes the script. - postMessage without origin checks.
- DNS rebinding: an attacker domain re-resolves to an internal IP, so the browser considers an internal service "same-origin" with the attacker's page.
- Browser bugs and extensions: out of scope for application testing but explain why browsers also ship site isolation and
Cross-Origin-*headers (COOP, CORP, COEP) to harden the boundary against side-channel attacks like Spectre. - XSS: the master bypass. Script injected into the origin is the origin.
Other policies that complement SOP
| Mechanism | Controls |
|---|---|
Content-Security-Policy |
Which origins scripts/styles/frames may load from; mitigates XSS |
X-Frame-Options / frame-ancestors |
Who may frame your page (clickjacking) |
SameSite cookies |
Whether cookies travel on cross-site requests |
Cross-Origin-Resource-Policy |
Who may embed your resources |
Cross-Origin-Opener-Policy |
Isolates your window from cross-origin openers |
Sec-Fetch-* request headers |
Lets servers see whether a request is same-origin, same-site, or cross-site |
Security relevance, summarized
| Attack | Relationship to SOP |
|---|---|
| XSS | Runs in-origin; SOP offers no protection after injection |
| CSRF | Works because sending is allowed; defenses (tokens, SameSite) fill the gap |
| CORS misconfiguration | Server intentionally lets the wrong origin read |
| Clickjacking | Framing is allowed unless the target forbids it |
Open redirect, postMessage bugs |
Abuse cross-origin communication channels |
| DNS rebinding, SSRF via the browser | Manipulate what counts as an origin or reach |
| Subdomain takeover | Same-site foothold that can set or read parent-domain cookies |
Hands-on exercises
- Origin quiz. For
https://shop.example.com:443/a, decide same-origin and same-site for ten URLs you invent, includinghttp://, ports,example.co.ukandx.github.iovariants. Verify origins withnew URL(url).originin the Console. - Watch SOP block a read. Open
https://example.comand run in its Console:fetch("https://www.iana.org/").then(r=>r.text()).then(console.log). Note the CORS error. Open the Network tab: was the request sent anyway? (It may be, with the response hidden from JS.) - Watch CORS allow it. Request a resource with a permissive policy, for example
fetch("https://httpbin.org/get").then(r=>r.json()).then(console.log)from any page; read theAccess-Control-Allow-Originresponse header in the Network tab. - Inspect a preflight. From the Console, run
fetch("https://httpbin.org/put",{method:"PUT",headers:{"X-Test":"1"}})and look in the Network tab for theOPTIONSrequest and its response headers. - Frame boundaries. Create a local file with an
<iframe src="https://example.com">. Trydocument.querySelector("iframe").contentDocumentin the Console and read the error. Then check whether a site refuses to be framed (look forX-Frame-Optionsorframe-ancestors). - Cookies across subdomains. In the Application tab, look at cookies on a site you log in to. Note any cookie with a leading dot in
Domain. Which subdomains receive it? - Read
Sec-Fetch-Site. In the Network tab on a Chromium browser, open a request's headers and findSec-Fetch-Site,Sec-Fetch-Mode, andSec-Fetch-Dest. Trigger a request from a different site and see how the value changes.
Run exercises against sites you own, controlled practice targets or public test endpoints. Do not try to read other people's authenticated data.
Checklist
- I can define origin and compute same-origin for any pair of URLs.
- I can explain eTLD+1 and why the Public Suffix List exists.
- I know the difference between same-origin and same-site and which features use each.
- I can list what SOP allows (embedding, sending) and blocks (reading).
- I can explain simple versus preflighted CORS requests and the role of credentials.
- I can name four common CORS misconfigurations.
- I can explain why CSRF works despite SOP.
Key takeaways
- An origin is scheme, host and port; a site is scheme plus eTLD+1. They are different units.
- SOP blocks cross-origin reads, not cross-origin sends.
- CORS loosens SOP and is only as safe as the allow-list and the credentials policy.
- Sibling subdomains are same-site but cross-origin, so subdomain bugs are high impact.
- XSS defeats SOP because the code runs inside the origin.
Further reading
- MDN: "Same-origin policy", "Cross-Origin Resource Sharing (CORS)", "Site isolation" and the
Sec-Fetch-Siteheader - WHATWG HTML Standard: origin; WHATWG Fetch Standard (CORS protocol)
- Public Suffix List (publicsuffix.org)
- PortSwigger Web Security Academy: Same-origin policy, CORS, CSRF, clickjacking
- OWASP HTML5 Security Cheat Sheet and Testing Guide: Testing Cross Origin Resource Sharing