NOTE

2.15 Browser Same-Origin Policy and Cross-Origin Access

Historical notes on the browser same-origin policy, cross-origin restrictions, and CORS.

Computer NetworksCreated Updated 2 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What Is the Same Origin?

Two URLs have the same origin when their (scheme, host, port) tuple is identical.

The following table gives examples relative to http://store.company.com/dir/page.html:

URL Result Reason
http://store.company.com/dir2/other.html Success Only the path differs
http://store.company.com/dir/inner/another.html Success Only the path differs
https://store.company.com/secure.html Failure Different scheme (https and http)
http://store.company.com:81/dir/etc.html Failure Different port (80 is the default for http)
http://news.company.com/dir/other.html Failure Different domain (news and store)

2. What Is Cross-Origin Access?

When JavaScript on the current page accesses a resource from a different origin, it is cross-origin access. For example, a user visits https://www.taobao.com and logs in. After login, the cookie is set under https://www.taobao.com. If the user visits https://cart.taobao.com, it cannot access the cookie set under https://www.taobao.com because the origins differ.

3. Cross-Origin Resource Restrictions

  • Operations prohibited across origins:
    • Data-storage restrictions:
      • LocalStorage and IndexedDB are separated by origin. Each origin has its own storage space, and JavaScript from one origin cannot read or write data from another origin.
      • The same-origin restriction for cookies is mainly about domains and is unrelated to ports or schemes. A user can read and write cookies for the current domain and its parent domain.
    • JavaScript API restrictions:
      • JavaScript from origin A cannot manipulate the DOM of a page from origin B.
    • Network-response restrictions:
      • For XHR requests, the browser compares returned data with the current page’s origin. If it is cross-origin, the data is filtered.
  • Operations allowed across origins:
    • Cross-origin writes are allowed (links, redirects, form submissions).
    • Cross-origin resource embedding is allowed (script, img, video, …).

4. How to Solve Cross-Origin Problems

Use CORS.

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.

CORS allows browsers to access cross-origin resources through HTTP headers such as Access-Control-Allow-Origin: *.

Nginx.md

5. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub