Spring Security默认的退出登录URL为/logout,退出登录后,Spring Security会做如下处理:
- 是当前的Sesion失效;
- 清除与当前用户关联的RememberMe记录;
- 清空当前的SecurityContext;
- 重定向到登录页。
1.自定义退出登录
配置中新增:
Controller中添加和/signout/success对应的方法:.and()
.logout()
// 退出 url
.logoutUrl("/signout")
// 退出成功地址
.logoutSuccessUrl("/signout/success")
// 删除浏览器 cookies
.deleteCookies("JSESSIONID")
配置免拦截登出接口:@GetMapping("/signout/success")
public String signout() {
return "退出成功,请重新登录";
}
.antMatchers("/login.html","/code/image","/signout/success").permitAll()
方式二:通过自定义退出处理器
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* <p>
* Description:[登出处理器]
* </p>
*
* @author shf
* @version 1.0
* @date Created on 2020/4/30 18:06
*/
@Component
public class MyLogOutSuccessHandler implements LogoutSuccessHandler {
@Override
public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
httpServletResponse.setContentType("application/json;charset=utf-8");
httpServletResponse.getWriter().write("退出啦,请重新登录");
}
}
配置新增
// 退出成功地址
// .logoutSuccessUrl("/signout/success")
// 配置自定义处理器
.logoutSuccessHandler(logOutSuccessHandler)