我目前正在尝试在Spring Boot 2中使用Spring Security实现应用程序的注销机制。
我的Spring Security注销配置如下:
http
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout.html"))
.logoutSuccessHandler(logoutSuccessHandler)
.addLogoutHandler(handler1)
.addLogoutHandler(handler2)
.clearAuthentication(false);
使用这个配置,Spring将两个处理器添加到LogoutFilter
中,同时将Spring自己的SecurityContextLogoutHandler
作为处理器链中的最后一个处理器。
我们面临的问题是,在我们自定义的LogoutSuccessHandler
中,我需要访问安全上下文中存储的一些变量,但即使在将.clearAuthentication(boolean clearAuthentication)
设置为false
时,上下文也会在SecurityContextLogoutHandler
中被清除。
我真正不理解的是SecurityContextLogoutHandler
中logout
方法的实现方式。
public void logout(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) {
Assert.notNull(request, "HttpServletRequest required");
if (invalidateHttpSession) {
HttpSession session = request.getSession(false);
if (session != null) {
logger.debug("Invalidating session: " + session.getId());
session.invalidate();
}
}
if (clearAuthentication) {
SecurityContext context = SecurityContextHolder.getContext();
context.setAuthentication(null);
}
SecurityContextHolder.clearContext();
}
即使我将
clearAuthentication
设置为false,由于该方法的最后一行SecurityContextHolder.clearContext();
会清除它,因此实际上并没有任何意义。那么
clearAuthentication
标志的意义是什么?如果需要保留Authentication,该如何操作?