Spring Security 实战 - 退出
2018-11-21 本文已影响101人
紫霞等了至尊宝五百年
原理
- 清除
Cookie
- 清除当前用户的
remember-me
记录 - 使当前
session
失效 - 清空当前的
SecurityContext
- 重定向到登录界面
Spring Security
的退出请求(默认为/logout
)由LogoutFilter过滤器拦截处理
实现
主页中添加退出链接
配置MerryyouSecurityConfig
源码分析
LogoutFilter#doFilter
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
// 1 匹配到/logout请求
if (requiresLogout(request, response)) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
// 2 清空Cookie、remember-me、session和SecurityContext
this.handler.logout(request, response, auth);
// 3 重定向到注册界面
logoutSuccessHandler.onLogoutSuccess(request, response, auth);
return;
}
chain.doFilter(request, response);
}
- CookieClearingLogoutHandler清空Cookie
- PersistentTokenBasedRememberMeServices清空remember-me
- SecurityContextLogoutHandler 使当前session无效,清空当前的SecurityContext
CookieClearingLogoutHandler#logout
Cookie置为nullPersistentTokenBasedRememberMeServices#logout
清空persistent_logins表中记录SecurityContextLogoutHandler#logout
使当前session失效
清空当前的SecurityContext
AbstractAuthenticationTargetUrlRequestHandler#handle
获取配置的跳转地址
跳转请求