Same-Origin Policy (SOP)
A critical security mechanism that restricts how a document or script loaded by one origin can interact with a resource from another origin.
Detailed Explanation
SOP is the baseline security model of the web. It prevents a malicious script on `evil.com` from reading your emails on `gmail.com`. An 'origin' is defined by the combination of protocol, domain, and port. While SOP is essential, it can be bypassed for legitimate reasons using CORS (Cross-Origin Resource Sharing).
Quick Summary
The Same-Origin Policy is the browser's default rule that scripts on one origin can't read responses from another. It's the foundation of web security, CORS is the controlled exception, not a replacement.
Key Takeaways
- Origin = scheme + host + port. `https://a.com` and `http://a.com` are different origins.
- SOP blocks reads, not requests. A cross-origin POST still happens, the response just isn't readable to JS without CORS.
- Embedded resources (images, scripts, CSS) load cross-origin by default but expose less data to JS.
- `document.domain`, `postMessage`, and CORS are the three legitimate cross-origin escape hatches.
- Subdomains (`a.example.com` vs `b.example.com`) are different origins despite the shared site.
When to use it
- Explaining why fetch() to a third-party API fails, it's not a network error, it's SOP without CORS.
- Designing iframe-based widgets: SOP prevents the parent and iframe from reading each other unless they explicitly opt in via postMessage.
- Understanding why CSRF works despite SOP: requests are sent, only responses are blocked.
Common Mistakes
- Confusing SOP with CORS. SOP is the rule; CORS is the mechanism for relaxing it.
- Assuming a cross-origin POST that "appears to succeed" was secure, the server received and acted on it.
- Treating two subdomains as the same origin because they share cookies, they don't, for fetch purposes.
Same-Origin Policy (SOP), Frequently Asked
Why does CSRF work if SOP exists?
SOP blocks the attacker from *reading* the response, but the request still fires and the browser still sends cookies. CSRF doesn't need to read the response, just trigger a state change. That's why you need CSRF tokens or SameSite cookies in addition to SOP.
Is SOP enforced by the server or the browser?
The browser, entirely. A native script or curl call ignores SOP completely. That's why server-side authorization checks are non-negotiable, SOP only protects browser-mediated access.