Spring Security 登出
# 默认退出处理逻辑
- 使当前session失效
- 清除配置的
RememberMe
认证, 会清空数据库中的token
- 清空
SecurityContextHolder
- 重定向到
/login?logout
关键类
LogoutConfigurer
观察发发现, /logout
针对多种请求方式
注意的一点是 loginUrl()
的注解
The URL that triggers log out to occur (default is "/logout"). If CSRF protection
is enabled (default), then the request must also be a POST. This means that by
default POST "/logout" is required to trigger a log out. If CSRF protection is
disabled, then any HTTP method is allowed.
this.logoutRequestMatcher = new OrRequestMatcher(
new AntPathRequestMatcher(this.logoutUrl, "GET"),
new AntPathRequestMatcher(this.logoutUrl, "POST"),
new AntPathRequestMatcher(this.logoutUrl, "PUT"),
new AntPathRequestMatcher(this.logoutUrl, "DELETE")
);
#自定义配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/").permitAll()
.and()
.logout().permitAll()
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.clearAuthentication(true)
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
.and()
.rememberMe()
.tokenValiditySeconds(60)
.tokenRepository(persistentTokenRepository())
.userDetailsService(userDetailsService)
.and()
.csrf()
.disable();
}
#解释
-
logout()
登出
-
logoutUrl()
访问地址会触发登出逻辑, 默认情况下
CSRF
自动开启, 请求必须是POST
, 为了方便这里采用GET
方式实际情况要设置为
POST
-
logoutSuccessUrl()
登出成功后, 重定向地址
-
logoutSuccessHandler()
登出成功之后的处理, 如果指定了, 那么
logoutSuccessUrl
就不会生效,需要自定义一个实现
LogoutSuccessHandler
的实现类。 -
addLogoutHandler()
添加登出时的Handler,LogoutHandler 即在程序执行logout时一起参与执行其中的处理逻辑
SecurityContextLogoutHandler
默认会加到最后处理实现类:
PersistentTokenBasedRememberMeServices
TokenBasedRememberMeServices
移除TokenCookieClearingLogoutHandler
清楚CookieCsrfLogoutHandler
移除CSRF TOKENSecurityContextLogoutHandler
HeaderWriterLogoutHandler
-
clearAuthentication()
登出后清除
Authentication
-
invalidateHttpSession()
登出后, 是否清空当前session
-
deleteCookies()
清空指定的Cookie
#LogoutSuccessHandler
/**
* 自定义登出成功处理器
*/
@Slf4j
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
@Autowired
private ObjectMapper mapper;
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
String username = authentication.getName();
response.setContentType("application/json;charset=utf-8");
log.info("退出成功, 用户名{}",username);
response.sendRedirect("/login");
}
}
配置类添加
@Bean
public LogoutSuccessHandler logoutSuccessHandler(){
return new MyLogoutSuccessHandler();
}
#参考:
https://blog.csdn.net/mrleeyongsheng/article/details/78886184