如何跨域發送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吧。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM