I'm currently trying to implement a logout mechanism for our application in Spring Boot 2 with Spring Security.
My logout configuration for spring security is:
http
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout.html"))
.logoutSuccessHandler(logoutSuccessHandler)
.addLogoutHandler(handler1)
.addLogoutHandler(handler2)
.clearAuthentication(false);
With this configuration Spring adds both handlers to the LogoutFilter along with Spring's own SecurityContextLogoutHandler as the last handler in the handler's chain.
The problem we are facing is that in our custom LogoutSuccessHandler I need to have access to some variables stored in the Authentication in the security context but the context is cleared in the SecurityContextLogoutHandler even when the .clearAuthentication(boolean clearAuthentication) is set to false.
What I really don't understand is the implementation of the logout method in SecurityContextLogoutHandler.
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();
}
Even when I set the clearAuthentication to false, it doesn't really matter because the last line of the method SecurityContextHolder.clearContext(); will clear it anyway.
What is the point of the clearAuthentication flag and how to retain the Authentication if I need to?