What does SecurityContextLogoutHandler do, and which cleanup tasks are NOT its responsibility?
answer
- clears SecurityContextHolder
- invalidates HttpSession
- NOT cookies / NOT remember-me
- invalidateHttpSession + clearAuthentication flags
- cookies -> CookieClearingLogoutHandler
basics
~10 sSecurityContextLogoutHandler clears the SecurityContextHolder (removing the current Authentication) and invalidates the HttpSession. It does not delete cookies or remember-me tokens — separate handlers do that.
solid answer
~40 sSecurityContextLogoutHandler is the default LogoutHandler and does two things: it clears the SecurityContextHolder (so the request is no longer authenticated) and, if invalidateHttpSession is true (the default), it calls HttpSession.invalidate(). It also has clearAuthentication (default true) controlling whether the context's Authentication is nulled. What it does NOT do: it does not delete browser cookies, and it does not cancel remember-me tokens. Those are handled by other LogoutHandlers — CookieClearingLogoutHandler for deleteCookies(), and the RememberMeServices implementation (which is itself a LogoutHandler) for the remember-me cookie. The logout() DSL wires all of these together, so the leaf's 'context + session + cookies' behavior is the sum of several handlers, not one class.
code
java · 14 lines// Tuning the default handler via the DSL
http.logout(logout -> logout
.invalidateHttpSession(true) // SecurityContextLogoutHandler.setInvalidateHttpSession(true)
.clearAuthentication(true) // SecurityContextLogoutHandler.setClearAuthentication(true)
.deleteCookies("JSESSIONID") // adds a CookieClearingLogoutHandler
);
// Programmatic logout inside a controller
@PostMapping("/custom-logout")
public String logout(HttpServletRequest req, HttpServletResponse res) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
new SecurityContextLogoutHandler().logout(req, res, auth); // clears context + invalidates session
return "redirect:/login?logout";
}go deeper
Know it clears the context and invalidates the session.
Correctly separate its responsibilities from cookie/remember-me handlers and name the flags.
Discuss ordering (read session before invalidation) and the persistent-token deletion nuance.
Relate session invalidation to session-fixation defense and the SecurityContextRepository lifecycle.
## The class `SecurityContextLogoutHandler` implements the `LogoutHandler` interface: ```java void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication); ``` It is the **default** logout handler that the `logout()` DSL always registers. Its job is to tear down the **in-memory and session-level** authentication state. ## What it actually does 1. **Invalidate the HttpSession.** If `invalidateHttpSession` is `true` (the default), it fetches the existing session (without creating one) and calls `session.invalidate()`. This drops *all* server-side session attributes, not just Spring Security's. The old `JSESSIONID` becomes invalid. 2. **Clear the SecurityContext.** It obtains the context from the `SecurityContextHolder`. If `clearAuthentication` is `true` (default), it calls `context.setAuthentication(null)`. It then calls `SecurityContextHolder.clearContext()` to remove the thread-local context entirely. Two tunable flags: - `setInvalidateHttpSession(boolean)` — DSL: `.invalidateHttpSession(true|false)`. - `setClearAuthentication(boolean)` — DSL: `.clearAuthentication(true|false)`. ## What it does NOT do (common interview trap) The leaf description bundles 'deleting remember-me/cookies' with this handler, but strictly: - **Deleting arbitrary cookies** (e.g. `JSESSIONID`) is done by **`CookieClearingLogoutHandler`**, registered when you call `.deleteCookies(...)`. It writes a `Set-Cookie` with `Max-Age=0`. - **Cancelling the remember-me cookie** is done by the **`RememberMeServices`** bean, because implementations like `TokenBasedRememberMeServices` and `PersistentTokenBasedRememberMeServices` *also implement `LogoutHandler`*. On logout they clear the `remember-me` cookie (and for the persistent variant, delete the server-side token row). - **Publishing the logout event** is done by `LogoutSuccessEventPublishingLogoutHandler` (fires `LogoutSuccessEvent`). So the full default cleanup is a **composite** of several handlers; `SecurityContextLogoutHandler` owns only context + session. ## Ordering and idempotency Handlers run in registration order inside a `CompositeLogoutHandler`. Because `SecurityContextLogoutHandler` invalidates the session, any handler that needs to read session data should run *before* it. The handler is safe to call even when there is no session (it won't create one) or no authentication. ## When to tune the flags - Set `invalidateHttpSession(false)` if you want to keep non-security session data across logout (rare; usually you want a clean session to avoid **session fixation** leftovers). - Set `clearAuthentication(false)` only in unusual flows where a downstream handler still needs the `Authentication` — generally leave it `true`. ## Manual use You can call it programmatically (e.g. in a controller doing custom logout): ```java new SecurityContextLogoutHandler().logout(request, response, auth); ```
- If you configure deleteCookies("remember-me"), do you still need remember-me's own LogoutHandler?For TokenBasedRememberMeServices, clearing the cookie is enough because the token is self-contained. For PersistentTokenBasedRememberMeServices there is also a server-side token row that must be deleted, which the RememberMeServices LogoutHandler handles; deleteCookies alone would leave the persistent token valid.
- Why is invalidating the session important beyond clearing the SecurityContext?The SecurityContext is per-request thread-local, but the session persists across requests. If you cleared only the context, the same JSESSIONID could still carry the stored SecurityContext (via HttpSessionSecurityContextRepository) on the next request. Invalidating the session prevents reuse and mitigates session-fixation leftovers.
saying these in an interview costs you the question
- Claiming SecurityContextLogoutHandler deletes cookies or remember-me tokens itself.
- Saying it logs the user out of the database or revokes their password.
- Thinking clearing the SecurityContext alone (without invalidating the session) fully logs the user out.