Mario Trucco
Mario Trucco

Reputation: 2011

Can I add a maximum expiry date to a session cookie?

I have set a session cookie, which doesn't have any expiry date and will therefore be deleted when the browser is closed.

Now I would like to add a maximum expiry date, meaning that

Notice that I don't want to set a "regular" expiry date because that would make my cookie persistent, failing to be deleted when the browser is closed before the expiry date.

The only solution I found is to have a second, persistent, cookie, with the maximum expiry date: I manually delete my first cookie if that second one is not found (expired). Since I would like to write as little information as possible in cookies, I'd prefer if there were another way.

After @CBroe's comment, I'm adding that the cookie is generated on the client side and I don't have an associated server side session where to store a last access timestamp

2018 update

After starting a bounty on this question, I got a couple of answers. Thank you. As a feedback, which could possibly better clarify the purpose of my question, please notice that I am not looking for code to set a persistent cookie or to implement the solution that I already have (set a second persistent cookie). I was hoping for some other creative suggestions. At the moment, I could use Zeeshan's hint and set the timestamp in the value (I would append it to the actual value). That answer is therefore so far the best candidate for being awarded the bounty.

Upvotes: 7

Views: 3616

Answers (2)

Zeeshan Anjum
Zeeshan Anjum

Reputation: 974

if you want to keep cookie as session cookie you can not set expiry. so you can either set timestamp as cookie value or create new cookie and set value as timestamp.

var timestamp = (new Date()).getTime()
document.cookie = "cookiename=value;  path=/";
document.cookie = "expirycookie="+timestamp+";  path=/";

for only client side solution you can set interval to check cookie timestamp value. add below code to all your pages

   var interval = setInterval(function(){
         var timeStamp = getCookie('expirycookie') 
         if(!timeStamp){clearInterval(interval); return}
         var cookieDuration = 5*60*1000 //expire cookie after 5 min
         if(timeStamp < (new Date()).getTime() - cookieDuration){
           //cookie expired delete here
           document.cookie = 'cookiename=value; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
           document.cookie = 'expirycookie=value; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
          clearInterval(interval)
        }
      },1000)

function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') c = c.substring(1);
    if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
  }
  return "";
}

Upvotes: 1

Vipul Gulhane
Vipul Gulhane

Reputation: 833

Cookie::setMaxAge(int)

in Java we have to specify an expiration time, you can use the setMaxAge(int) method of javax.servlet.http.Cookie. It takes as a parameter the number of seconds before the cookie will expire.

For example, for a five minute expiration, we would do the following :-

// Create a new cookie for userID from a fictitious
// method called getUserID
Cookie cookie = new Cookie ("userID", getUserID());

// Expire the cookie in five minutes (5 * 60)
cookie.setMaxAge( 300 );

When the cookie is sent back to the browser, using HttpServletResponse.addCookie(Cookie), it will only be returned by the browser until the expiration date occurs. If you'd prefer, you can also specify a negative value for setMaxAge(int), and the cookie will expire as soon as the browser exits. Note however that not everyone will shutdown their browser, and it might be available for minutes, hours even days. Finally, specifying a value of zero will expire the cookie instantly.

Here is full Java Servlet example.

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class HelloForm extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

      // Create cookies for first and last names.      
      Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
      Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));

      // Set expiry date after 24 Hrs for both the cookies.
      firstName.setMaxAge(60*60*24);
      lastName.setMaxAge(60*60*24);

      // Add both the cookies in the response header.
      response.addCookie( firstName );
      response.addCookie( lastName );

      // Set response content type
      response.setContentType("text/html");

      PrintWriter out = response.getWriter();
      String title = "Setting Cookies Example";
      String docType =
         "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";

      out.println(docType +
         "<html>\n" +
            "<head>
               <title>" + title + "</title>
            </head>\n" +

            "<body bgcolor = \"#f0f0f0\">\n" +
               "<h1 align = \"center\">" + title + "</h1>\n" +
               "<ul>\n" +
                  "  <li><b>First Name</b>: "
                  + request.getParameter("first_name") + "\n" +
                  "  <li><b>Last Name</b>: "
                  + request.getParameter("last_name") + "\n" +
               "</ul>\n" +
            "</body>
         </html>"
      );
   }
}

And HtML file will be

<html>
   <body>
      <form action = "HelloForm" method = "GET">
         First Name: <input type = "text" name = "first_name">
         <br />
         Last Name: <input type = "text" name = "last_name" />
         <input type = "submit" value = "Submit" />
      </form>
   </body>
</html>

Upvotes: 0

Related Questions