Spring Security provides features to enable a user to log out and be redirected to a specified page. The URI of the LogoutController is typically mapped to the logout link in the UI. The complete listing of LogoutController is as follows:
@Controller
public class LogoutController {
@RequestMapping(value = "/secure/logout", method = RequestMethod.GET)
public String logout(HttpServletRequest request, HttpServletResponse response) {
Authentication auth =
SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
new SecurityContextLogoutHandler()
.logout(request, response, auth);
request.getSession().invalidate();
}
return "redirect:/secure/welcome";
}
}
The following definitions explain the workings of the preceding code block:
- if (auth != null): If there is a valid authentication, end the session.
- new SecurityContextLogoutHandler().logout(request, response, auth): SecurityContextLogoutHandler performs a logout by removing the authentication information from SecurityContextHolder.
- return "redirect:/secure/welcome": This redirects to the secure welcome page.