Dynamically set session cookie max age

2.2k views Asked by At

I'm using Jetty's session management and want to implement a simple login with a 'Remember me' option.

So if the user doesn't want to be remembered, I want the JSESSIONID cookie to live until the browser session is closed. If the user opts-in to be remembered, the cookie will expire within 30 days.

I'm using SessionCookieConfig to configure the cookie details on startup and I can't change that per request.

So is there a way to dynamically change the max age per login request? The only way I can see is to get the cookie from the request and then change the max age:

//in LoginServlet
doPost(HttpServletRequest request, HttpServletResponse response) {
    //... Get remember me option from request
    request.getCookies();
    //... Find cookie in array by name JSESSIONID
    if (rememberMe) {
        sessionCookie.setMaxAge(60 * 60 * 24 * 30);
    } else {
        sessionCookie.setMaxAge(-1);
    }
}

However I want to refrain as much as possible from dealing with the session and leave it to the container.

Is there another option?

1

There are 1 answers

2
Jan On

The jsessionid cookie is handled by the container and so I wouldn't recommend that you try and repurpose it. Instead, there's a wealth of info on stackoverflow on how to implement a "remember me" function: try here.