How to perform logout programmatically in spring 3

老子叫甜甜 提交于 2019-12-05 00:12:26
Dirk Lachowski

It depends. If it's ok for your app to place the logged out user on the "you have been logged out" page then this may be ok. But you can't be sure if your user will really be logged out (e.g. if the browser is suppressing the redirect).

Programmatically you can log out this way:

public void logout(HttpServletRequest request, HttpServletResponse response) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
          if (auth != null){    
             new SecurityContextLogoutHandler().logout(request, response, auth);
          }
        SecurityContextHolder.getContext().setAuthentication(null);
    }

As @LateralFractal pointed out, if you haven't changed the defaults of the SecurityContextLogoutHandler (see https://github.com/spring-projects/spring-security/blob/3.2.x/web/src/main/java/org/springframework/security/web/authentication/logout/SecurityContextLogoutHandler.java#L96 ) you can cut this down to

public void logout(HttpServletRequest request) {
    new SecurityContextLogoutHandler().logout(request, null, null);
}

or even (although it's a bit ugly)

public void logout() {
    HttpServletRequest request =
        ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
            .getRequest();
    new SecurityContextLogoutHandler().logout(request, null, null);

See https://stackoverflow.com/a/9767869/1686330 for some background on getting the HttpServletRequest.

HttpSession session = request.getSession();
session.invalidate();
SecurityContextHolder.clearContext();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!