Reputation: 9492
I am trying to set a cookie with Expires date:
response.Cookies.Append("theKey", value, new CookieOptions() { Expires = DateTime.Now.AddMonths(12) });
the cookie is stored in the browser but is not sent in a subsequent cross-site web request.
When I try set the cookie without the Expires
date, the cookie is sent, but it is stored in the browser only while the browser is open (session cookie).
It is a cross-site request. The javascript code that calls the function is:
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);
Is there a way to send a cookie containing Expires
date in a cross-site request?
Both the client web app and the function app (that attempts to set the cookie) use https.
This is the HTTP response setting the cookie with expiration date:
Upvotes: 3
Views: 8621
Reputation: 9492
The solution is to set the cookie's SameSite
attribute. This allows sending the cookie along with cross-site requests from JavaScript code.
Possible values of SameSite
attribute (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite):
In .NET Core, the cookie needs to be explicitly set with the SameSite
attribute, since the default is lax
:
response.Cookies.Append("theCookie", value, new CookieOptions()
{
Expires = DateTime.Now.AddMonths(12),
SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None
});
Upvotes: 9
Reputation: 4517
You server needs to include the following CORS response header:
Access-Control-Allow-Credentials: true
in addition to the Access-Control-Allow-Origin
header you're already sending.
Without the ACAC header, the browser will not process any Set-Cookie
response headers from the origin. I suspect the cookie is being set by a Set-Cookie response header in a different response.
Upvotes: 5