public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout() //开启logout配置
.invalidateHttpSession(true) //默认true, 当登出时会销毁当前session
.clearAuthentication(true) //默认true, 清除认证标记
.and()
.csrf().disable();
}
}
当clearAuthentication设置为true的时会SecurityContextLogoutHandler 下的logout 方法
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
Assert.notNull(request, "HttpServletRequest required");
if (this.invalidateHttpSession) {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
if (this.logger.isDebugEnabled()) {
this.logger.debug(LogMessage.format("Invalidated session %s", session.getId()));
}
}
}
if (this.clearAuthentication) {
SecurityContext context = SecurityContextHolder.getContext();
context.setAuthentication(null);
}
SecurityContextHolder.clearContext();
}
我不太理解的是,当设置为true时,会将context中的Authentication设置为null,但如果不设置为null我好像没看到有什么影响,SecurityContextHolder.clearContext() 会将当前线程的认证信息清除。SecurityContextPersistenceFilter最后的finally也会将session中的认证信息清除。所以clearAuthentication 清除认证信息到底是为了什么。