NOTE

2.15 浏览器同源策略以及跨域

1. 什么是同源 两个URL的 (协议,主机,端口) 三元组相同的话就叫做同源 下表给出了相对http://store.company.com/dir/page.html同源检测的示例 2. 什么是跨域 当前页面的javascript访问了非同源的资源,就叫做跨域 3. 跨域资源限制 4. 如何解决跨域问题 使用CORS。

计算机网络创建于 更新于 约 2 分钟读完historical

这是历史学习笔记,可能存在过时或不完整的理解。

1. 什么是同源

两个URL的 (协议,主机,端口) 三元组相同的话就叫做同源

下表给出了相对http://store.company.com/dir/page.html同源检测的示例:

URL 结果 原因
http://store.company.com/dir2/other.html 成功 只有路径不同
http://store.company.com/dir/inner/another.html 成功 只有路径不同
https://store.company.com/secure.html 失败 不同协议 ( https和http )
http://store.company.com:81/dir/etc.html 失败 不同端口 ( http:// 80是默认的)
http://news.company.com/dir/other.html 失败 不同域名 ( news和store )

2. 什么是跨域

当前页面的javascript访问了非同源的资源,就叫做跨域 比如用户访问https://www.taobao.com登录,登录之后cookie是种在https://www.taobao.com下的, 如果用户访问https://cart.taobao.com,那么访问不了种在https://www.taobao.com下的cookie,因为非同源

3. 跨域资源限制

  • 跨域禁止的操作
    • 数据存储限制:
      • LocalStorage、IndexedDB 以源进行分割,每个源都拥有自己单独的存储空间,一个源中的 JavaScript 脚本不能对其它源的数据进行读写操作
      • cookie 的同源限制主要体现在域方面,与端口,协议无关。用户可以读写当前域以及当前域对应父域下的 cookie。
    • JavaScript API限制:
      • A源页面的js无法操作B源的DOM
    • 网络响应限制
      • XHR请求数据,浏览器会对返回的数据和当前页面对比是否同源,非同源则直接过滤
  • 跨域允许的操作
    • 允许跨域写操作(link、redirect、表单提交)
    • 允许跨域资源嵌入(script、img、video…)

4. 如何解决跨域问题

使用CORS。

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.

所谓CORS就允许浏览器跨域访问资源的HTTP头Access-Control-Allow-Origin: * Nginx.md

5. 参考

讨论

使用 GitHub 账号参与讨论,评论会保存在 GitHub Issues 中。在 GitHub 查看