Spring Security默认的退出登录URL为/logout,退出登录后,Spring Security会做如下处理:
- 使当前的sesion失效;
- 清除与当前用户关联的RememberMe记录;
- 清空当前的SecurityContext;
- 重定向到登录页;
Spring Security允许我们通过配置来更改上面这些默认行为。
一、自定义退出登录行为
我们在Spring Security配置中添加如下配置:
...... .and() .logout() .logoutUrl("/signout") //.logoutSuccessUrl("/signout/success") .deleteCookies("JSESSIONID") .and() ......
上面配置了退出登录的URL为/signout,退出成功后跳转的URL为/signout/success,退出成功后删除名称为JSESSIONID的cookie。
在LoginController中添加/signout/success对应的方法:
@ResponseBody @RequestMapping("/signout/success") public String signout() { return "退出成功,请重新登录"; }
接着将/signout/success添加到免认证路径里。启动项目,登录后访问/signout:
可看到退出成功,并且请求重定向到了/signout/success。
除了指定logoutUrl外,我们也可以通过logoutSuccessHandler指定退出成功处理器来处理退出成功后的逻辑:
.and() .logout() .logoutUrl("/signout") .logoutSuccessUrl("/signout/success") .logoutSuccessHandler(logoutSuccessHandler) //处理退出成功 .deleteCookies("JSESSIONID")
在包com.goldwind.handler下创建类CustomLogoutSuccessHandler :
package com.goldwind.handler; import org.springframework.http.HttpStatus; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.stereotype.Service; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @Author: zy * @Description:自定义退出成功逻辑 * @Date: 2020/2/16 */ @Service public class CustomLogoutSuccessHandler 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("退出成功,请重新登录"); } }
效果和上面一样:
参考文章:
[1] Spring Security退出登录(转载)