Martin Staufcik
Martin Staufcik

Reputation: 9492

Cookie is not sent with CORS web request

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:

enter image description here

Upvotes: 3

Views: 8621

Answers (2)

Martin Staufcik
Martin Staufcik

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):

  • strict - the cookie is not sent for cross-site requests
  • lax (the default) - the cookie is sent for cross-site requests only when the user follows a regular link (e.g. clicking)
  • none (previous default) - the cookie is sent for cross-site requests

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

roryhewitt
roryhewitt

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-Cookieresponse headers from the origin. I suspect the cookie is being set by a Set-Cookie response header in a different response.

Upvotes: 5

Related Questions