我有一个应用程序,其中我将会话超时设置为1小时。但我不希望如果用户关闭浏览器并再次打开它,他必须再次登录。为此,我需要一种方法以某种方式刷新每个请求的cookie到期时间。
我正在使用具有弹簧安全性的弹簧靴。如何实现此功能?
答案 0 :(得分:1)
我使用Interceptor解决了它。我们的想法是拦截http请求并修改jsessionid cookie并将到期时间设置为您想要的任何值。这将允许浏览器重新打开后重用cookie。默认情况下,jsessionid cookie的最大年龄等于-1,这意味着一旦浏览器关闭,cookie就会过期。
productname = driver.find_elements_by_xpath("//div[@class='product-title']")
oldprice = driver.find_elements_by_css_selector("span.old-price-text")
discount = driver.find_elements_by_css_selector("div.discount > span")
saleprice = driver.find_elements_by_css_selector("span.new-price-text")
这个拦截器可以注册如下:
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;
}
}
}
}
}
答案 1 :(得分:0)
Baeldung有一个使用Filter的解决方案。 @ https://www.baeldung.com/spring-security-session
public class SessionFilter implements Filter {
@Override
public void doFilter(
ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
Cookie[] allCookies = req.getCookies();
if (allCookies != null) {
Cookie session =
Arrays.stream(allCookies).filter(x -> x.getName().equals("JSESSIONID"))
.findFirst().orElse(null);
if (session != null) {
session.setHttpOnly(true);
session.setSecure(true);
res.addCookie(session);
}
}
chain.doFilter(req, res);
}
}
答案 2 :(得分:0)
只能在拦截器的preHandle中创建、更新和删除cookie。
如果你想在控制器被调用后添加一个cookie,那么必须使用ControllerAdvice
@ControllerAdvice
public class CookieAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType,
Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType,
MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request, ServerHttpResponse response) {
Cookie cookie = new Cookie("cookieName", cookieValue);
ServletServerHttpResponse resp = (ServletServerHttpResponse)response;
resp.getServletResponse().addCookie(cookie);
return body;
}
}