Spring Boot会话过期管理配置后不自动跳转及未登录误跳转问题咨询
问题解决方案
前置修改:解决配置冲突问题
你当前的三处配置中Session Cookie名称不统一:application.yml中为TEST_SESSION、web.xml中为WMS_JSESSIONID、Security退出逻辑删除的是SESSIONID,会导致会话失效逻辑异常,首先统一所有Cookie名称为SESSIONID,Spring Boot项目可直接删除web.xml中的session-config配置,避免和yml配置优先级冲突。
问题1:3分钟超时不生效,仅手动刷新才跳转的解决
Session是服务端存储的机制,默认不会主动向前端推送过期状态,且前端AJAX请求默认不会处理服务端返回的302重定向,所以用户操作时不会触发跳转,按以下步骤修改:
- 修改
application.yml配置,统一Cookie名称:
servlet: contextPath: / session: cookie: name: SESSIONID max-age: 180 timeout: 180
- 修改
SecurityConfig中退出逻辑,对应Cookie名和配置一致:
.logout().clearAuthentication(true) .logoutUrl("/logout") .logoutSuccessUrl("/login?logout") .deleteCookies("SESSIONID") .invalidateHttpSession(true) .permitAll()
- 自定义认证入口,区分普通请求和AJAX请求返回不同结果:
@Component public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { String xRequestedWith = request.getHeader("X-Requested-With"); if ("XMLHttpRequest".equals(xRequestedWith)) { response.setContentType("application/json;charset=utf-8"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getWriter().write("{\"code\":401,\"msg\":\"会话已过期,请重新登录\"}"); } else { response.sendRedirect(request.getContextPath() + "/login"); } } }
替换SecurityConfig中原有的authenticationEntryPoint为上述自定义实现,同时前端新增全局AJAX拦截器,捕获401状态码直接跳转登录页。
- 如果需要实现无操作自动跳转,可在前端登录成功后开启180秒倒计时,倒计时结束直接触发跳转,或者每隔30秒向后端发一次心跳请求检测会话状态。
问题2:未登录用户刷新也跳会话过期页的解决
默认的invalidSessionUrl配置会对所有无效会话统一跳转,不区分是否登录过,按以下步骤自定义策略区分:
- 自定义无效会话处理策略:
@Component public class CustomInvalidSessionStrategy implements InvalidSessionStrategy { @Override public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException { Cookie[] cookies = request.getCookies(); boolean hasLoginFlag = false; if (cookies != null) { for (Cookie cookie : cookies) { if ("LOGIN_FLAG".equals(cookie.getName()) && "1".equals(cookie.getValue())) { hasLoginFlag = true; // 清除过期的登录标记 cookie.setMaxAge(0); cookie.setPath("/"); response.addCookie(cookie); break; } } } if (hasLoginFlag) { // 已登录用户过期跳转带提示的登录页 response.sendRedirect(request.getContextPath() + "/login?sessionExpired=true"); } else { // 未登录用户直接跳转普通登录页 response.sendRedirect(request.getContextPath() + "/login"); } } }
- 在登录成功处理器
spAuthenticationSuccessHandler中新增登录标记Cookie写入逻辑:
// 登录成功后执行 Cookie loginFlag = new Cookie("LOGIN_FLAG", "1"); loginFlag.setPath("/"); loginFlag.setMaxAge(180); // 和session超时时间保持一致 response.addCookie(loginFlag);
- 替换
SecurityConfig中的sessionManagement配置:
.sessionManagement() .invalidSessionStrategy(customInvalidSessionStrategy) // 注入上面自定义的策略 .and()
内容的提问来源于stack exchange,提问作者ABC
相关产品推荐
相关产品推荐

