SOP
The Same-Origin Policy (SOP) is a critical security mechanism in web browsers that restricts how documents or scripts loaded from one origin can interact with resources from another origin. It prevents malicious websites from accessing or manipulating data from other sites without permission.
What is an Origin?
An origin is defined by three components:
Protocol (e.g.,
http,https)Host (e.g.,
www.example.com)Port (e.g.,
80,443)
Two URLs have the same origin if all three components match. Otherwise, they are considered cross-origin.
Examples of Same-Origin and Cross-Origin
https://example.com
https://example.com
Yes
Protocol, host, and port match.
https://example.com
http://example.com
No
Different protocols (https vs http).
https://example.com
https://api.example.com
No
Different hosts (example.com vs api.example.com).
https://example.com:80
https://example.com:443
No
Different ports (80 vs 443).
How SOP Works
The Same-Origin Policy restricts:
Access to DOM: Scripts from one origin cannot access the DOM of a page from another origin.
Example: A script on
https://malicious.comcannot read or modify the DOM ofhttps://example.com.
Network Requests: Scripts cannot make certain types of requests (e.g.,
XMLHttpRequestorfetch) to a different origin unless the server explicitly allows it using CORS (Cross-Origin Resource Sharing).Cookies and Storage: Cookies and local storage data are isolated by origin. A script cannot access cookies or storage from another origin.
Examples of SOP in Action
Example 1: Accessing the DOM
A script on
https://malicious.comtries to access the DOM ofhttps://example.com:
Example 2: Making Network Requests
A script on
https://malicious.comtries to fetch data fromhttps://api.example.com:
Exceptions to SOP
CORS (Cross-Origin Resource Sharing):
Allows servers to specify which origins can access their resources.
Example: If
https://api.example.comincludes the headerAccess-Control-Allow-Origin: https://example.com, thenhttps://example.comcan access its resources.
JSONP (JSON with Padding):
A workaround for making cross-origin requests using
<script>tags (deprecated in favor of CORS).
PostMessage API:
Allows secure communication between windows or iframes from different origins.
Embedded Resources:
Some resources like images, scripts, and stylesheets can be loaded cross-origin, but they cannot be accessed or manipulated by scripts.
Why is SOP Important?
Security: Prevents malicious websites from stealing sensitive data (e.g., cookies, session tokens) or performing unauthorized actions on behalf of the user.
Privacy: Protects user data from being accessed by unauthorized parties.
Isolation: Ensures that web applications from different origins cannot interfere with each other.
Last updated