我想为x分钟的登录会话设置超时。
我创建了一个SessionListener
:
public class SessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent event) {
event.getSession().setMaxInactiveInterval(60 *15);
}
@Override
public void sessionDestroyed(HttpSessionEvent event) { }
}
哪些会创建超时为15分钟的会话,但我想在用户登录后设置此超时。否则,如果您在登录页面等待超过15分钟并尝试登录,则会话已被破坏,您无法登录(并且启动了AccessDeniedHandler类)。
答案 0 :(得分:1)
最后我有一个解决方案。即使用户未经过身份验证,Spring创建会话的主要原因是csrf令牌,因此只要页面打开,Spring就会创建会话。我所做的是在创建会话时设置会话而不会超时。
public class SessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent event) {
event.getSession().setMaxInactiveInterval(0);
}
@Override
public void sessionDestroyed(HttpSessionEvent event) { }
}
然后,一旦用户通过身份验证(使用登录页面),我就会为当前会话设置超时:
public class LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
@Autowired
private RedirectStrategy redirectStrategy;
@Override
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
// Set session timeout when user is authenticated
request.getSession().setMaxInactiveInterval(5);
redirectStrategy.sendRedirect(request, response, targetUrl);
}
}
通过这种方式,用户只要需要就可以保持登录页面,并且永远不会破坏会话。