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

  1. 是当前的Sesion失效;
  2. 清除与当前用户关联的RememberMe记录;
  3. 清空当前的SecurityContext;
  4. 重定向到登录页。

    1.自定义退出登录

    配置中新增:
    1. .and()
    2. .logout()
    3. // 退出 url
    4. .logoutUrl("/signout")
    5. // 退出成功地址
    6. .logoutSuccessUrl("/signout/success")
    7. // 删除浏览器 cookies
    8. .deleteCookies("JSESSIONID")
    Controller中添加和/signout/success对应的方法:
    1. @GetMapping("/signout/success")
    2. public String signout() {
    3. return "退出成功,请重新登录";
    4. }
    配置免拦截登出接口:
    1. .antMatchers("/login.html","/code/image","/signout/success").permitAll()

方式二:通过自定义退出处理器

  1. import org.springframework.http.HttpStatus;
  2. import org.springframework.security.core.Authentication;
  3. import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
  4. import org.springframework.stereotype.Component;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.io.IOException;
  9. /**
  10. * <p>
  11. * Description:[登出处理器]
  12. * </p>
  13. *
  14. * @author shf
  15. * @version 1.0
  16. * @date Created on 2020/4/30 18:06
  17. */
  18. @Component
  19. public class MyLogOutSuccessHandler implements LogoutSuccessHandler {
  20. @Override
  21. public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
  22. httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
  23. httpServletResponse.setContentType("application/json;charset=utf-8");
  24. httpServletResponse.getWriter().write("退出啦,请重新登录");
  25. }
  26. }

配置新增

  1. // 退出成功地址
  2. // .logoutSuccessUrl("/signout/success")
  3. // 配置自定义处理器
  4. .logoutSuccessHandler(logOutSuccessHandler)

image.png