Programatically logging a user out in Spring Security

So I use Spring Security to handle user authentication in most of my Web applications. Every now and then, you need to log a user out programmatically. For example, users perform some sort of operation that redirects to a success page and logs them out. Logging a user out is quite simple. You need use the logout method for the relevant LogoutHandlers in your application. You are always going to have to use the SecurityContextLogoutHandler. I generally use the “remember me token” so I also have to use the PersistentTokenBasedRememberMeServices. Below is a sample method that you could have in your controller.

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.Authentication;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.ui.logout.SecurityContextLogoutHandler;
import org.springframework.security.ui.rememberme.PersistentTokenBasedRememberMeServices; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class SampleController {
   @RequestMapping(value="/some_page.htm")
   public String somePage (HttpServletRequest request, HttpServletResponse response) {
        /* some business logic code */
      Authentication auth = SecurityContextHolder.getContext().getAuthentication();
      if (auth != null){    
         new SecurityContextLogoutHandler().logout(request, response, auth);
         new PersistentTokenBasedRememberMeServices().logout(request, response, auth);
      }
   }
}