同源策略的定义
Two URLs have the same origin if the protocol, port (if specified), and host are the same for both. You may see this referenced as the "scheme/host/port tuple", or just "tuple". (A "tuple" is a set of items that together comprise a whole — a generic form for double/triple/quadruple/quintuple/etc.)
同源策略/SOP(Same origin policy)是一种约定,由Netscape公司1995年引入浏览器,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,浏览器很容易受到XSS、CSFR等攻击。@t.cn/RplB1tL
所谓同源是指以下三者相同:
- 协议相同
- 域名相同(即便两个不同的域名指向同一个ip地址,也非同源)
- 端口相同
例子:
The following table gives examples of origin comparisons with the URL http://store.company.com/dir/page.html:
| URL | Outcome | Reason |
|---|---|---|
| store.company.com/dir2/other.… | Same origin | Only the path differs |
| store.company.com/dir/inner/a… | Same origin | Only the path differs |
| store.company.com/page.html | Failure | Different protocol |
| store.company.com:81/dir/page.ht… | Failure | Different port (http:// is port 80 by default) |
| news.company.com/dir/page.ht… | Failure | Different host |
同源策略限制的行为
如果非同源,共有三种行为受到限制:
- Cookie、LocalStorage 和 IndexDB 无法读取
- DOM 和 Js对象无法获得
- AJAX 请求不能发送
同源策略的目的
浏览器安全的基石是"同源政策"(same-origin policy)。
同源政策的目的,是为了保证用户信息的安全,防止恶意的网站窃取数据。
【以下例子很能说明问题】:
设想这样一种情况:A网站是一家银行,用户登录以后,又去浏览其他网站。如果其他网站可以读取A网站的 Cookie,会发生什么?
很显然,如果 Cookie 包含隐私(比如存款总额),这些信息就会泄漏。更可怕的是,Cookie 往往用来保存用户的登录状态,如果用户没有退出登录,其他网站就可以冒充用户,为所欲为。因为浏览器同时还规定,提交表单不受同源政策的限制。
由此可见,"同源政策"是必需的,否则 Cookie 可以共享,互联网就毫无安全可言了。
References
- 浏览器同源政策及其规避方法 www.ruanyifeng.com/blog/2016/0…
- Same-origin policy developer.mozilla.org/en-US/docs/…