Skip to main content

Same-Origin Policy and CORS

What is Same-Origin Policy and CORS?

Being the root of the web's security model, same-origin policy(SOP) is a client-side security mechanism (specifically targeting scripts running in the browser), that limits resouces of an origin can only be accessed through requests (e.g fetch API, XMLHttpRequest) from the same origin.

With same-origin policy, it helps to improve security by isolating malicious websites that would otherwise be able to access data of other websites through executing JavaScript if SOP is not enforced.

However, there are legitimate cases where accessing cross-origin resources is desirable or even necessary, such as fetching fonts or images from services hosted on other origins. Thus, Cross-Origin Resource Sharing (CORS) is introduced to tackle such scenarios.

CORS is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.

Train of Thoughts

Why is SOP enforced ?

✅ Answer

Imagine a self-hosted REST service that provides data for your website. Without SOP, any other websites can simply request your data thourgh simple fetch API or ajax.

In addition, browser can load and display resources from multiple sites at once, either with multiple tabs or embed resources through iframe, etc. This might introduce security issues where data might be exposed if embeded resources contains compromised scripts.

Thus, the main goal is to protect the sites that receive requests from cross-orgin sites.

Browsers implicitly don't trust the websites it visits and the requests sent by them, and it's the targeted server's responsibility to decide what origins are allowed to request for resources.

How is same origin defined ?

✅ Answer

Web content's origin is defined by the scheme (protocol), hostname (domain), and port of the URL used to access it. Check WHATWG SPEC for detail.

For two URLs to be considered as same origin, both URL must fulfill below restrictions:

  1. Same protocol, e.g both are http/https
  2. Same domain
  3. Same port (if given)

When is SOP applied ?

✅ Answer

Any other ways to get pass same-origin policy ?

✅ Answer

Deep Dive

What is blocked/permitted by the SOP ?

CORS in depth

There are two types of CORS request: simple requests, and preflight requests.

  • Simple request:
  • Preflight request:

🔗 References