如何在Spring中处理失败的注销?

时间:2019-04-17 14:04:02

标签: java spring session spring-security

在Spring Security中,我不会立即使会话无效,但是我正在LogoutSuccessHandler中进行会话(需要保留一些信息以供注销后调查) 这使我明白:如果注销出错,应该如何使会话无效?

HttpSecurity:

        http.authorizeRequests()
                ...
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(myLogoutSuccessHandler())
                .invalidateHttpSession(false) // session invalidated by logoutSuccessHandler.

和myLogutSuccessHandler():

public class MyLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler implements LogoutSuccessHandler {

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {

        ....

        // Invalidation of an old session
        HttpSession session = request.getSession(false);
        if (session != null) {
            logger.debug("Invalidating session: " + session.getId());
            session.invalidate();
        }

        ...

        super.onLogoutSuccess(request, response, authentication);
    }
}

这使我明白:如果注销出错,应该如何使会话无效?

谢谢

1 个答案:

答案 0 :(得分:1)

来自Javadoc:

  

LogoutHandler实现期望被调用以执行必要的清理,因此不应引发异常。

因此您的LogoutSuccessHandler将始终被呼叫。只要在实际使会话无效之前(或者只要被捕获),在您的onLogoutSuccess(..)方法中没有引发任何异常,您的代码将始终运行。

也许方法onLogoutSuccess()的名称不是很直观(可能更像afterLogout())。没有LogoutFailureHandler,因为注销将总是成功,因此将始终调用LogoutSuccessHandler的{​​{1}}。