Web Security: Same-origin Policy

 20th August 2020 at 2:19pm

Same-origin Policy 即同源策略,是 web 安全中的一项关键措施,用来决定浏览器在访问某个站点时,能否向非同源的另一站点请求数据。

Definition of an origin

两个站点仅在协议(http / https)、主机和端口同时相同时才算同源。

比如,对于 http://store.company.com/dir/page.html:

URLOutcomeReason
http://store.company.com/dir2/other.htmlSame originOnly the path differs
http://store.company.com/dir/inner/another.htmlSame originOnly the path differs
https://store.company.com/page.htmlFailureDifferent protocol
http://store.company.com:81/dir/page.htmlFailureDifferent port (http:// is port 80 by default)
http://news.company.com/dir/page.htmlFailureDifferent host

What is permitted and what is blocked?

什么情况下访问跨域资源是被允许的,什么情况下是被禁止的?

web.dev 的 文章 描述了常见网络请求的情况。MDN 的 文章 描述了网络请求、DOM API 以及 data storage 的情况。

网络请求是这其中最受重视的。一般来说:

  1. Cross-origin writes are typically allowed. Examples are links, redirects, and form submissions. Some HTTP requests require preflight.
  2. Cross-origin embedding is typically allowed:
    • JavaScript with <script src="…"></script>. Error details for syntax errors are only available for same-origin scripts.
    • CSS applied with <link rel="stylesheet" href="…">. Due to the relaxed syntax rules of CSS, cross-origin CSS requires a correct Content-Type header.
    • Images displayed by <img>.
    • Media played by <video> and <audio>.
    • External resources embedded with <object> and <embed>.
    • Fonts applied with @font-face. Some browsers allow cross-origin fonts, others require same-origin.
    • Anything embedded by <iframe>. Sites can use the X-Frame-Options header to prevent cross-origin framing.
  3. Cross-origin reads are typically disallowed, but read access is often leaked by embedding. For example, you can read the dimensions of an embedded image, the actions of an embedded script, or the availability of an embedded resource.

HTTP 提供了 CORS 机制来控制哪些跨域请求是被允许的。

Reference