Symfony Logout Handlers vs Logout Success Handlers

Important note: logout and logout success handlers are now deprecated in Symfony 5.1, instead there’s a new LogoutEvent to listen for and use.

Symfony’s security configuration for logout functionality in a firewall has a few handler keys that are worth digging into:

security:
# ...
firewalls:
main:
  # other config here, probably
  logout:
  handlers:
    - some.service_id
    # or...
    - Some\Fully\Qualified\ClassName
    success_handler: some.service_id

Logout Handlers

These are defined in the handlers key of the configuration above and the classes behind the listed services must implement LogoutHandlerInterface.

Logout handlers should perform actions related to logging the user out. For example, session based authentication might invalidate the session. In fact, this is something Symfony provides.

There can be multiple logout handlers in a given firewall. Multiple behaviors needed on logout? Build multiple handlers instead of trying to shove all the functionality into one.

Logout Success Handlers

The purpose of a success handler, set at the success_handler key in the configuration above, is to generate a Response object that will be returned to the user.

Logout sucess handlers must implement LogoutSuccessHandlerInterface. The default logout success handler generates a redirect to a taget url or path, specified like this in a security configuration:

security:
# ...
firewalls:
main:
# other config here, probably
logout:
path: /logout

How These Handlers Fit Together

Symfony uses these two interfaces in its LogoutListener. A simplified version:

$response = $logoutSuccessHandler->onLogoutSuccess($request);

foreach ($logoutHandlers as $logoutHandler) {
/** @var Symfony\Component\Security\Core\Authentication\Token\TokenInterface $authenticationToken */
$logoutHandler->logout($request, $response, $authenticationToken);
}

clearAuthenticationToken($authenticationToken);

returnResponseToUser($response);

The logout success handler is invoked to generate a HTTP response object. Then each logout handler is invoked with the incoming, logout HTTP request, the response, and the authentication token (the logged in user).

When to Use Logout and Logout Success Handlers

Use logout handlers when an application needs to perform some sort of cleanup when a user signs out. I recently implemented a logout handler that invalidated all active access tokens on an internal facing OAuth authentication server. When a user logs out, they would be logged out of all applications calling into the OAuth server: a behavior we wanted to enforce.

A success handler should be implemented when some custom behavior needs to happen to generate a logout response. The same app that invalidated access tokens also needed some custom response behavior for logout: we needed to ensure the user was redirected to a URL stored in the database. The custom handler looked up the URL and generated redirect response.