Skip to content

5.3.4 Logging out

Now that you’ve dealt with logging in, let’s flip to the other side of the authentication coin and see how you can enable a user to log out. Just as important as logging in to an application is logging out. To enable logout, you simply need to call logout on the HttpSecurity object as follows:

java
.and()
  .logout()

This sets up a security filter that intercepts POST requests to /logout. Therefore, to provide logout capability, you just need to add a logout form and button to the views in your application, as shown next:

html
<form method="POST" th:action="@{/logout}">
  <input type="submit" value="Logout"/>
</form>

When the user clicks the button, their session will be cleared, and they will be logged out of the application. By default, they’ll be redirected to the login page where they can log in again. But if you’d rather they be sent to a different page, you can call logoutSuccessUrl() to specify a different post-logout landing page, as shown here:

java
.and()
  .logout()
    .logoutSuccessUrl("/")

In this case, users will be sent to the home page following logout

Released under the MIT License.