gpt4 book ai didi

spring - 在 spring 的每个请求上刷新 cookie

转载 作者:行者123 更新时间:2023-12-04 00:32:12 25 4
gpt4 key购买 nike

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

我正在使用具有 Spring 安全性的 Spring Boot 。我怎样才能实现这个功能。?

最佳答案

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

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

}

}

这个拦截器可以注册如下:
@Component
public class WebMvcConfig extends WebMvcConfigurerAdapter{

@Override
public void addInterceptors(InterceptorRegistry registry){

registry.addInterceptor(new CookieExpiryRefresher());
}
}

关于spring - 在 spring 的每个请求上刷新 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49549436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com