QuestionsNetworking/Security

The same-origin policy

Browser Security ModelEasyNetworking/Security

What is the same-origin policy, what counts as an 'origin', and why does the web need it?

What it tests

Understanding the foundational browser isolation boundary that everything else (CORS, cookies, XSS impact) builds on.

Approach & answer

The same-origin policy (SOP) is the browser's foundational security boundary: script running on one ORIGIN cannot read data from a different origin. An ORIGIN is the triple of SCHEME + HOST + PORT — https://app.example.com:443. All three must match to be 'same-origin'; https vs http differs, app. vs api. differs, :443 vs :3000 differs. So https://example.com and http://example.com are different origins, as are example.com and www.example.com. Why the web needs it: browsers routinely hold your authenticated state for many sites at once (cookies, sessions). Without SOP, a malicious page you open in one tab could script requests to your bank in another tab, read the responses (which include your logged-in data because the browser attaches your cookies), and exfiltrate them — total cross-site data theft. SOP prevents that by isolating origins: evil.com's JavaScript cannot read the response from bank.com, cannot read bank.com's cookies or localStorage, and cannot reach into a cross-origin iframe's DOM. What SOP restricts is READING cross-origin responses via script; it does NOT block all cross-origin activity — the browser still SENDS many cross-origin requests (loading an <img>, <script>, <link> stylesheet, or submitting a form to another site all work, which is exactly why CSRF is possible). It's specifically the programmatic READING of the response, and access to another origin's DOM/storage, that's blocked. SOP is the default deny; CORS is the controlled, server-opt-in mechanism to RELAX it for specific cross-origin reads. Understanding SOP also explains the blast radius of XSS: because script runs WITH the origin's privileges, an attacker who injects script into your origin inherits full same-origin access — which is why XSS is so damaging and why the origin boundary is the thing you're protecting.

Use this technique when

Reasoning about cross-origin access; explaining why CORS exists; scoping the impact of XSS.

Code

Origin = scheme + host + port   (all three must match)

  https://app.example.com:443  vs
  ----------------------------------------------------
  https://app.example.com          SAME (default :443)
  http://app.example.com           DIFFERENT (scheme)
  https://api.example.com          DIFFERENT (host)
  https://app.example.com:3000     DIFFERENT (port)

SOP blocks: reading cross-origin RESPONSES via script; reading another
            origin's DOM, cookies, localStorage.
SOP allows: SENDING cross-origin requests (<img>,<script>,<form>) -> why CSRF exists.
Default-deny; CORS is the server's opt-in to relax it.

References