Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

refresh cookie on each request in spring

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.?

like image 978
ArslanAnjum Avatar asked Jan 28 '23 09:01

ArslanAnjum


1 Answers

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());
    }
}
like image 61
ArslanAnjum Avatar answered Jan 31 '23 08:01

ArslanAnjum