Cookie不会随CORS Web请求一起发送

问题描述 投票:0回答:2

我正在尝试使用过期日期设置cookie:

response.Cookies.Append("theKey", value, new CookieOptions() { Expires = DateTime.Now.AddMonths(12) });

cookie存储在浏览器中,但不会在后续的跨站点Web请求中发送。

当我尝试在没有Expires日期的情况下设置cookie时,会发送cookie,但只有在浏览器打开时才会将其存储在浏览器中(会话cookie)。

这是一个跨站点请求。调用该函数的javascript代码是:

var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, true);
xmlHttp.withCredentials = true;
xmlHttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        //console.log(this.responseText);
    }
};
xmlHttp.send(null);

有没有办法在跨站点请求中发送包含Expires日期的cookie?

客户端Web应用程序和功能应用程序(尝试设置cookie)都使用https。

这是设置有效期限的cookie的HTTP响应:

enter image description here

javascript .net-core cors asp.net-core-2.1
2个回答
1
投票

您的服务器需要包含以下CORS响应头:

 Access-Control-Allow-Credentials: true

除了你已经发送的Access-Control-Allow-Origin标题。

如果没有ACAC标头,浏览器将不会处理来自源的任何Set-Cookieresponse标头。我怀疑cookie是由不同响应中的Set-Cookie响应头设置的。


1
投票

解决方案是省略cookie的samesite属性。这允许发送cookie以及来自javascript代码的跨站点请求。

samesite属性的可能值(https://www.owasp.org/index.php/SameSite):

  • 严格 - 不为跨站点请求发送cookie
  • lax - 仅当用户遵循常规链接时才会发送cookie用于跨站点请求
  • (未设置) - 为跨站点请求发送cookie

在.NET Core中,需要明确设置cookie以不创建samesite属性,因为默认值为lax

response.Cookies.Append("theCookie", value, new CookieOptions() 
{ 
    Expires = DateTime.Now.AddMonths(12), 
    SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None 
});
© www.soinside.com 2019 - 2024. All rights reserved.