How to manually log out a user with spring security?

Erik picture Erik · Apr 20, 2011 · Viewed 93.7k times · Source

Probably the answer is simple: How can I manually logout the currently logged in user in spring security? Is it sufficient to call:

SecurityContextHolder.getContext().getAuthentication().setAuthenticated(false); 

?

Answer

Grzegorz Oledzki picture Grzegorz Oledzki · Apr 20, 2011

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.