I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security 5:

1. Overview

The Spring Security framework provides very flexible and powerful support for authentication. Together with user identification, we'll typically want to handle user logout events and, in some cases, add some custom logout behavior. One such use case could be for invalidating a user cache or closing authenticated sessions.

For this very purpose, Spring provides the LogoutHandler interface, and in this tutorial, we'll take a look at how to implement our own custom logout handler.

2. Handling Logout Requests

Every web application that logs users in must log them out someday. Spring Security handlers usually control the logout process. Basically, we have two ways of handling logout. As we're going to see, one of them is implementing the LogoutHandler interface.

2.1. LogoutHandler Interface

It is possible to add as many logout handlers as we need to our application. The one requirement for the implementation is that no exceptions are thrown. This is because handler actions must not break the application state on logout.

For example, one of the handlers may do some cache cleanup, and its method must complete successfully. In the tutorial example, we'll show exactly this use case.

2.2. LogoutSuccessHandler Interface

On the other hand, we can use exceptions to control the user logout strategy. For this, we have the LogoutSuccessHandler interface and the onLogoutSuccess method. This method may raise an exception to set user redirection to an appropriate destination.

Furthermore, it's not possible to add multiple handlers when using a LogoutSuccessHandler type, so there is only one possible implementation for the application. Generally speaking, it turns out that it's the last point of the logout strategy.

The important part to note from the above configuration is the addLogoutHandler method. We pass and trigger our CustomLogoutHandler at the end of logout processing. The remaining settings fine-tune the HTTP Basic Auth.