How to manually log out a user with spring security?

It's hard for me to say for sure if your code is enough. However standard Spring-security's implementation of logging out is different. If you took a look at SecurityContextLogoutHandler you would see they do:

    SecurityContextHolder.clearContext();

Moreover they optionally invalidate the HttpSession:

    if (invalidateHttpSession) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
    }

You may find more information in some other question about logging out in Spring Security and by looking at the source code of org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler.


In Servlet 3.0 container Spring logout functionality is integrated with servlet and you just invoke logout() on your HttpServletRequest. Still need to write valid response content.

According to documentation (Spring 3.2):

The HttpServletRequest.logout() method can be used to log the current user out.

Typically this means that the SecurityContextHolder will be cleared out, the HttpSession will be invalidated, any "Remember Me" authentication will be cleaned up, etc.


I use the same code in LogoutFilter, reusing the LogoutHandlers as following:

public static void myLogoff(HttpServletRequest request, HttpServletResponse response) {
    CookieClearingLogoutHandler cookieClearingLogoutHandler = new CookieClearingLogoutHandler(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
    SecurityContextLogoutHandler securityContextLogoutHandler = new SecurityContextLogoutHandler();
    cookieClearingLogoutHandler.logout(request, response, null);
    securityContextLogoutHandler.logout(request, response, null);
}

You can also use SessionRegistry as:

sessionRegistry.getSessionInformation(sessionId).expireNow();

If you want to force logout in all sessions of a user then use getAllSessions method and call expireNow of each session information.

Edit
This requires ConcurrentSessionFilter (or any other filter in the chain), that checks SessionInformation and calls all logout handlers and then do redirect.