在 spring 的每个请求上刷新 cookie [英] refresh cookie on each request in spring

查看:57
本文介绍了在 spring 的每个请求上刷新 cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,其中我将会话超时设置为 1 小时.但是我不希望如果用户关闭浏览器并再次打开它,他必须再次登录.为此,我需要一种方法来以某种方式刷新每个请求的 cookie 到期时间.

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

推荐答案

我已经使用 Interceptor 解决了.这个想法是拦截http请求并修改jsessionid cookie并将到期时间设置为您想要的任何值.这将允许浏览器在重新打开后重新使用 cookie.默认情况下,jsessionid cookie 的 max age 等于 -1,这意味着它的 cookie 会在浏览器关闭后立即过期.

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());
    }
}

这篇关于在 spring 的每个请求上刷新 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆