同源策略(英語: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. 

外部链接 编辑