I have an application in which I have set the session timeout to be 1 hour. But I do not want that if the user closes his browser and opens it again, he has to login again. For that I need a method to somehow refresh cookie expiry time on each request.
I am using spring boot with spring security. How can I achieve this functionality.?
I have solved it using Interceptor. The idea is to intercept http request and modify the jsessionid cookie and set expiry time to whatever value you want. This would allow the cookie to be reused by the browser once it is re-opened. By default jsessionid cookie has max age equal to -1 which means that it cookie would expire as soon as browser is closed.
public class CookieExpiryRefresher extends HandlerInterceptorAdapter {
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, //
Object handler, ModelAndView modelAndView) throws Exception {
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies){
if (cookie.getName().contentEquals("JSESSIONID")){
if (cookie.getValue().contentEquals(request.getSession().getId())){
cookie.setMaxAge(60*60*5);
cookie.setPath("/");
response.addCookie(cookie);
break;
}
}
}
}
}
And this interceptor can be registered as follows:
@Component
public class WebMvcConfig extends WebMvcConfigurerAdapter{
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(new CookieExpiryRefresher());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With