如何跨域发送cookie

此文的跨域方法为CORS

参考链接

浏览器同源政策及其规避方法
跨域资源共享 CORS 详解
Cookie 的 SameSite 属性
当跨域遇到Cookie与SameSite
Cross-Site Request Forgery is dead!

如何跨域发送cookie

前端:

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

后端返回的response中增加这些字段

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:8080 (必须与请求网页一致的域名)

满足这些要求后还不一定能发送Cookie,需要注意Cookie中的SameSite字段。

  • 当SameSite为Lax时,是否传cookie,需要看你请求方法的类型,具体类型有可以查看Cookie 的 SameSite 属性
  • 当SameSite为None时,是否传cookie,需要你设置Secure才能传输,也就是https。

文章中说Chrome80已经将SameSite默认设置为Lax。从Firefox 69开始进行测试,后续的版本也会将SameSite设置为Lax。
chrome官方文档说76版本已经开始SameSite默认设置为Lax。
官方文档:Cookies default to SameSite=Lax Network / Connectivity

我的例子

我目前的版本chrome版本 81.0.4044.113 (正式版本),Cookie未设置SameSite,使用ajax发送get,post请求,可以发送cookie。
请求后console中打印的警告信息 。

A cookie associated with a cross-site resource at http://127.0.0.1/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests 
if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at 
https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.  

前端html

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
  var xmlhttp;
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      console.log(xmlhttp.responseText);
    }
  }
  xmlhttp.open("GET","http://127.0.0.1:8082/test/post",true);
 //xmlhttp.open("POST","http://127.0.0.1:8082/test/post",true);
  xmlhttp.withCredentials = true;
  xmlhttp.send();
}
</script>
</head>
<body>

<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">cors</button>
<div id="myDiv"></div>

</body>
</html>

request和response
request和response

chrome地址栏输入 chrome://flags/ 。将SameSite by default cookies 设置为 enable,这就是浏览器 SameSite默认值的设置。.
samesite

重新再发post,ajax get请求,不能发送cookie,这样看来我这个版本的 浏览器还没有将SameSite默认设置为Lax。

特殊情况

在公司的电脑上版本为66的 chrome上,发现SameSite设置为none,secure也设置了,发的也是https请求。无论跨域非跨域都发送不了,注意是非跨域都不行。导致了一个用户一直登陆不了,每次请求都是set一个新的cookie。

总结

跨域携带cookie太难了,还是用token吧。

posted @ 2020-04-22 23:03  Always_July  阅读(2424)  评论(0编辑  收藏  举报