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:

  1. Protocol (e.g., http, https)

  2. Host (e.g., www.example.com)

  3. 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

URL 1
URL 2
Same Origin?
Reason

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:

  1. Access to DOM: Scripts from one origin cannot access the DOM of a page from another origin.

    • Example: A script on https://malicious.com cannot read or modify the DOM of https://example.com.

  2. Network Requests: Scripts cannot make certain types of requests (e.g., XMLHttpRequest or fetch) to a different origin unless the server explicitly allows it using CORS (Cross-Origin Resource Sharing).

  3. 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.com tries to access the DOM of https://example.com:

Example 2: Making Network Requests

  • A script on https://malicious.com tries to fetch data from https://api.example.com:


Exceptions to SOP

  1. CORS (Cross-Origin Resource Sharing):

    • Allows servers to specify which origins can access their resources.

    • Example: If https://api.example.com includes the header Access-Control-Allow-Origin: https://example.com, then https://example.com can access its resources.

  2. JSONP (JSON with Padding):

    • A workaround for making cross-origin requests using <script> tags (deprecated in favor of CORS).

  3. PostMessage API:

    • Allows secure communication between windows or iframes from different origins.

  4. 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