同源策略(英语:Same-origin policy)是指在Web浏览器中,允许某个网页脚本访问另一个网页的数据,但前提是这两个网页必须有相同的URI主机名端口号,一旦两个网站满足上述条件,这两个网站就被认定为具有相同来源。此策略可防止某个网页上的恶意脚本通过该页面的文档对象模型访问另一网页上的敏感数据。

同源策略对Web应用程序具有特殊意义,因为Web应用程序广泛依赖于HTTP cookie[1]来维持用户会话,所以必须将不相关网站严格分隔,以防止丢失数据泄露。

值得注意的是同源策略仅适用于脚本,这意味着某网站可以通过相应的HTML标签[2]访问不同来源网站上的图像CSS动态加载脚本等资源。而跨站请求伪造就是利用同源策略不适用于HTML标签的缺陷。

相同来源网站举例 编辑

下表列出哪些URLURL http://www.example.com/dir/page.html 属于相同来源:

URL 结果 原因
http://www.example.com/dir/page2.html 只有路径不同
http://www.example.com/dir2/other.html 只有路径不同
http://username:password@www.example.com/dir2/other.html 只有路径不同
http://www.example.com:81/dir/other.html 不同端口(若未标明,http:// 默认端口号为80)
https://www.example.com/dir/other.html[失效链接] 不同协议httpshttp
http://en.example.com/dir/other.html 不同域名
http://example.com/dir/other.html 不同域名(需要完全匹配)
http://v2.www.example.com/dir/other.html 不同域名(需要完全匹配)

另见 编辑

参考文献 编辑

  1. ^ IETF [rfc:6265 HTTP State Management Mechanism, Apr, 2011]
  2. ^ Kemp, John. Security on the Web. 2011-02-04 [2018-07-24]. (原始内容存档于2020-09-23). The same-origin policy states that a document from one unique origin may only load resources from the origin from which the document was loaded. In particular this applies to XMLHttpRequest calls made from within a document. Images, CSS and dynamically-loaded scripts are not subject to same-origin policy. 

外部链接 编辑