跨域之同源策略 Same-origin policy

Posted Fogwind

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了跨域之同源策略 Same-origin policy相关的知识,希望对你有一定的参考价值。

同源策略是浏览器中最基本的隔离潜在恶意文件的安全策略,他限制了来自不同源(origin)的文档或脚本之间的相互作用。

何谓同源

跨域之URL中介绍过一个URL的标准格式如下:

协议类型://服务器地址(必要时需加上端口号)/路径/文件名

对比URL的标准格式,这里的同源就是指:

  1. 协议类型相同(protocol)
  2. 服务器地址相同(host,也可以叫域名相同)
  3. 端口相同(port,一般默认为80)

下面是维基百科上的例子。

假如一个URL为http://www.example.com/dir/page.html,下表中列举的URL与该URL的关系(Success表示同源,Failure表示不同源):

Compared URLOutcomeReason
http://www.example.com/dir/page2.html Success Same protocol, host and port
http://www.example.com/dir2/other.html Success Same protocol, host and port
http://username:password@www.example.com/dir2/other.html Success Same protocol, host and port
http://www.example.com:81/dir/other.html Failure Same protocol and host but different port
https://www.example.com/dir/other.html Failure Different protocol
http://en.example.com/dir/other.html Failure Different host
http://example.com/dir/other.html Failure Different host (exact match required)
http://v2.www.example.com/dir/other.html Failure Different host (exact match required)
http://www.example.com:80/dir/other.html Depends Port explicit. Depends on implementation in browser.

IE特例(摘自MDN)

在处理同源策略的问题上,IE存在两个主要的不同之处。

  • 授信范围(Trust Zones):两个相互之间高度互信的域名,如公司域名(corporate domains),不遵守同源策略的限制。
  • 端口:IE未将端口号加入到同源策略的组成部分之中,因此 http://company.com:81/index.html 和http://company.com/index.html  属于同源并且不受任何限制。

同源策略的限制

同源策略是为了保证用户信息的安全而设置的,如果两个页面不同源,他们在以下交互上受到限制(摘自浏览器同源政策及其规避方法):

  1. Cookie、LocalStorageIndexDB 无法读取。
  2. DOM 无法获得。
  3. AJAX 请求不能成功。

有些时候为了实现某些需求,可以使用一些特殊手段突破同源策略的限制,在之后的学习中再总结。

以上是关于跨域之同源策略 Same-origin policy的主要内容,如果未能解决你的问题,请参考以下文章

ajax跨域之---服务器端代理实现

前端跨域之Jsonp的原生请求和Jquery的ajax请求,简单易懂。

fetch.js是啥

前端之跨域

同源策略与跨域问题解决

Ajax跨域--同源策略 & 什么是跨域