Course – LSS – NPI (cat=Security/Spring Security)
announcement - icon

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

>> CHECK OUT THE COURSE

1. Overview

This article is building on top of our Form Login tutorial and is going to focus on the how to configure Logout with Spring Security.

Further reading:

Spring Security: Authentication with a Database-backed UserDetailsService

A quick guide to to create a custom database-backed UserDetailsService for authentication with Spring Security.

Introduction to Spring Method Security

A guide to method-level security using the Spring Security framework.

Spring Security - Redirect to the Previous URL After Login

A short example of redirection after login in Spring Security

2. Basic Configuration

The basic configuration of Spring Logout functionality using the logout() method is simple enough:

@Configuration
@EnableWebSecurity
public class SecSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
          //...
          .logout()
          //...
   }
   //...
}

And using XML configuration:

<http>

    ...    
    <logout/>

</http>

The element enables the default logout mechanism – which is configured to use the following logout url: /logout which used to be /j_spring_security_logout before Spring Security 4.

3. The JSP and the Logout Link

Continuing this simple example, the way to provide a logout link in the web application is:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
   <head></head>
   <body>
      <a href="<c:url value="/logout" />">Logout</a>
   </body>
</html>

4. Advanced Customizations

4.1. logoutSuccessUrl()

After the logout process is performed successfully, Spring Security will redirect the user to a specified page. By default, this is the root page (“/”) but this is configurable:

//...
.logout()
.logoutSuccessUrl("/afterlogout.html")
//...

This can also be done using XML configuration:

<logout logout-success-url="/afterlogout.html" />

Depending on the application, a good practice is to redirect the user back to the login page:

//...
.logout()
.logoutSuccessUrl("/login.html")
//...

4.2. logoutUrl()

Similar to other defaults in Spring Security, the URL that actually triggers the logout mechanism has a default as well – /logout.

It is, however, a good idea to change this default value, to make sure that no information is published about what framework is used to secure the application:

.logout()
.logoutUrl("/perform_logout")

And through XML:

<logout 
  logout-success-url="/anonymous.html" 
  logout-url="/perform_logout" />

4.3. invalidateHttpSession and deleteCookies

These two advanced attributes control the session invalidation as well as a list of cookies to be deleted when the user logs out. As such, invalidateHttpSession allows the session to be set up so that it’s not invalidated when logout occurs (it’s true by default).

The deleteCookies method is simple as well:

.logout()
.logoutUrl("/perform_logout")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")

And the XML version:

<logout 
  logout-success-url="/anonymous.html" 
  logout-url="/perform_logout"
  delete-cookies="JSESSIONID" />

4.4. logoutSuccessHandler()

For more advanced scenarios, where the namespace is not flexible enough, the LogoutSuccessHandler bean from the Spring Context can be replaced by a custom reference:

@Bean
public LogoutSuccessHandler logoutSuccessHandler() {
    return new CustomLogoutSuccessHandler();
}

//...
.logout()
.logoutSuccessHandler(logoutSuccessHandler());
//...

The equivalent XML configuration is:

<logout 
  logout-url="/perform_logout"
  delete-cookies="JSESSIONID"
  success-handler-ref="customLogoutSuccessHandler" />

...
<beans:bean name="customUrlLogoutSuccessHandler" />

Any custom application logic that needs to run when the user successfully logs out can be implemented with custom logout success handler. For example – a simple audit mechanism keeping track of the last page the user was on when they triggered logout:

public class CustomLogoutSuccessHandler extends 
  SimpleUrlLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired 
    private AuditService auditService; 

    @Override
    public void onLogoutSuccess(
      HttpServletRequest request, 
      HttpServletResponse response, 
      Authentication authentication) 
      throws IOException, ServletException {
 
        String refererUrl = request.getHeader("Referer");
        auditService.track("Logout from: " + refererUrl);

        super.onLogoutSuccess(request, response, authentication);
    }
}

Also, keep in mind that this custom bean has the responsibility to determine the destination to which the user is directed after logging out. Because of this, pairing the logoutSuccessHandler attribute with logoutSuccessUrl is not going to work, as both cover similar functionality.

5. Conclusion

In this example, we started by setting up a simple logout sample with Spring Security, and we then discussed the more advanced options available.

The implementation of this Spring Logout Tutorial can be found in the GitHub project – this is an Eclipse-based project, so it should be easy to import and run as it is.

When the project runs locally, the sample HTML can be accessed at:

http://localhost:8080/spring-security-mvc-login/login.html

Course – LSS (cat=Security/Spring Security)

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

>> CHECK OUT THE COURSE
res – Security (video) (cat=Security/Spring Security)
Comments are closed on this article!