12

浏览器同源策略和跨域

 3 years ago
source link: https://doumao.cc/index.php/%E7%BC%96%E7%A8%8B/%E6%B5%8F%E8%A7%88%E5%99%A8%E5%90%8C%E6%BA%90%E7%AD%96%E7%95%A5%E5%92%8C%E8%B7%A8%E5%9F%9F.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

什么是同源策略

同源策略是指在浏览器中,允许某个网页的脚本访问另一个网页的数据(如Cookie),但前提是这两个网页必须是同源的,同源指的是两个网页协议相同域名相同端口相同

同源策略可防止某个网页的恶意脚本,访问另一网页上的敏感数据,保证用户信息的安全。

假设A网站是一家银行,用户登录以后,又去浏览其他网站。如果其他网站可以读取A网站的Cookie,因为Cookie往往是我们登录的凭证,这种场景就会存在极大的风险。

同源策略保证了我们信息的安全,但有些场景下,我们需要突破同源策略的限制,也就是跨域。

平时开发中,我们遇到比较多的跨域场景是Cookie跨域Ajax跨域

Cookie跨域

默认情况下,只有同源的网页间才能共享Cookie。如果两个网页的一级域名相同,但是二级域名不同,两个网页间是无法共享Cookie的。

可以通过在服务器设置Cookie时,指定Cookie的所属域名为一级域名。

Set-Cookie: key=value; domain=.example.com; path=/

这样的话,二级域名和三级域名不用做任何设置,都可以读取这个 Cookie。

Ajax跨域

同源策略规定了Ajax只能请求同源的网址,否者浏览器会报错。

XMLHttpRequest cannot load http://api.alice.com.
Origin http://api.bob.com is not allowed by Access-Control-Allow-Origin.

JSONP

JSONP的原理是同源策略只适用于脚本,网站可以通过<script>来动态加载执行不同源的脚本文件。

function addScriptTag(src) {
  var script = document.createElement('script');
  script.setAttribute("type","text/javascript");
  script.src = src;
  document.body.appendChild(script);
}

window.onload = function () {
  addScriptTag('http://example.com/ip?callback=foo');
}

function foo(data) {
  console.log('Your public IP address is: ' + data.ip);
};

通过动态添加<script>元素,向服务器example.com发送请求。

服务器收到请求后,会将数据放到回调函数的参数位置并返回。下面是服务器的返回。

foo({
  "ip": "8.8.8.8"
});

由于是<script>请求的脚本,上面的返回会做为代码直接运行。

CORS,跨源资源分享,是跨域Ajax请求的根本解决方法。CORS需要浏览器和服务器同时支持。

具体可以看:跨域资源共享 CORS 详解

同源策略 - 维基百科

浏览器同源政策及其规避方法

跨域资源共享 CORS 详解


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK