Same-Origin, CSP, and CORS

· 2 min read · 528 Words · -Views -Comments

These three terms appear frequently in frontend security — here’s a summary. They also connect to related topics like same‑site, cross‑origin, XSS, and CSRF.

They seem varied, but are easier to grasp when tied to real scenarios:

  • Why the Same‑Origin Policy (SOP)?

    • “Same origin” means protocol, domain, and port all match. Asynchronous requests from a different origin are cross‑origin. For safety, browsers restrict XHR and similar requests via SOP. Without SOP, site A could freely request resources from site B without user awareness; B could read A’s data or manipulate DOM — unsafe. Note: HTML script and image tags aren’t subject to SOP.
    • The same resource requested via XHR (e.g., a script) or fonts loaded via CSS are subject to cross‑origin restrictions.
  • SOP isn’t enough — enter CSP

    • Even with SOP, if a page is injected with malicious scripts, XSS can still occur. Content Security Policy (CSP) narrows allowed sources and types. For example, if CSP only allows external JS, injected inline JS will error and not run.
  • SOP + CSP improves safety, but reduces flexibility — enter CORS

    • Sometimes site A legitimately needs resources from site B, and both trust each other. Cross‑Origin Resource Sharing (CORS) lets the server explicitly authorize allowed origins, enabling safe reuse.
    • Alternatives to CORS include reverse proxies, since backend services aren’t subject to SOP. In frontend development, when hitting a non‑local backend (different address), we often configure a proxy to avoid cross‑origin issues.
  • Same‑site vs. same‑origin

    • SOP is strict. A company might have many sites like a.111.com and b.111.com — different origins, but often needing limited sharing. “Same‑site” requires only the same eTLD+1. For example, opening B from A may reuse the same renderer process if same‑site and same execution context; B can access A’s window via window.opener.
  • Hotlink protection via Referer

    • Since script/img aren’t restricted by SOP, resources can be hotlinked. Servers can use the HTTP Referer header to block unauthorized use (403). Browsers don’t allow arbitrary client‑side modification of Referer, preventing trivial spoofing.

Final Thoughts

Seen together, these mechanisms evolved to balance security and flexibility. Once you understand the scenarios, they’re straightforward.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover