SpringBoot集成SpringSecurity ------登出操作

SpringBoot集成SpringSecurity ------登出操作

Scroll Down

Spring Security默认的退出登录URL为/logout,退出登录后,Spring Security会做如下处理:

  1. 是当前的Sesion失效;

  2. 清除与当前用户关联的RememberMe记录;

  3. 清空当前的SecurityContext;

  4. 重定向到登录页。

自定义退出登录

在Security 配置中添加一下配置:

 .and()
     .logout().logoutUrl("/logout")
     .logoutSuccessUrl("/login")
     // 配置注销成功的回调
     .deleteCookies("JSESSIONID")
     .permitAll()
 .and()

配置退出登录的URL为 /logout ,退出成功后的跳转URL为 /login ,指向登录URL。 退成成功后,删除cookie。

除了指定logoutUrl外,我们也可以通过logoutSuccessHandler指定退出成功处理器来处理退出成功后的逻辑:

    @Autowired
    CustomLogoutHandler customLogoutHandler;

  .and()
     .logout().logoutUrl("/logout")
    // 配置注销成功的回调
   .logoutSuccessHandler(customLogoutHandler) 
   .deleteCookies("JSESSIONID")
   .permitAll()
  .and()

CustomLogoutHandler 实现 LogoutSuccessHandler接口:

@Component
public class CustomLogoutHandler implements LogoutSuccessHandler {

    private Logger logger = LoggerFactory.getLogger(CustomLogoutHandler.class);

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        String username  = ((UserInfo)authentication.getPrincipal()).getUsername();
        logger.info("退出成功,用户名:{}", username);
        //重定向
        httpServletResponse.sendRedirect("/login");
    }
}