Reputation: 267077
I'm attempting to set a cookie which would last for 2 years. However, when I restart the browser, the cookie seems to get deleted.
The behavior seems random, sometimes the cookie is preserved on restart, but on the next restart its gone again.
Full headers returned by my page:
HTTP/1.1 200 OK
Content-Length: 16
x-response-time: 11ms
Set-Cookie: ___auth=853c780cf6cacb177fd641af543c2e23048730aab126c2ee2f93cf0b725f3f30ec425160ea225761bee9bd9c100a1b897031f9194a7564301a9849b6e932440bb299cadabe885ca108973000bf5c183e;
Expires=Fri, 10 Feb 2017 10:30:53 GMT; Path=/
Currently this is being run on http://localhost:8080
, not yet tested in production. Behavior happens in both chrome and firefox.
Any ideas?
Upvotes: 0
Views: 3457
Reputation: 6608
As you can see here, Expires attribute is deprecated in HTTP 1.1 in favor of Max-Age
. If you have set some age for a particular cookie, it can be seen as Max-age
in cookie like below
Set-Cookie: UserID=JohnDoe; Max-Age=3600; Version=1
But in your response, there's no Max-age set , so its considered as session cookie and is cleared on browser exit :-)
Set-Cookie: ___auth=853c780cf6cacb177fd641af543c2e23048730aab126c2ee2f93cf0b725f3f30ec425160ea225761bee9bd9c100a1b897031f9194a7564301a9849b6e932440bb299cadabe885ca108973000bf5c183e;
So create cookies using Cookie API like below and add them to HttpServletResponse in Servlet like this
Cookie cookie = new Cookie ("_auth", authString);
cookie.setMaxTime( 63072000 ); // time in seconds
response.addCookie(cookie);
With this, it should persist for 2 years :-)
Upvotes: 2