Spring Security Logout

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.

2. Basic Configuration

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

@Configuration
@EnableWebSecurity
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(final 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

Related posts:

Java Program to Perform Right Rotation on a Binary Search Tree
Java Program to Implement Sorted Singly Linked List
Basic Authentication with the RestTemplate
Java Program to Check whether Directed Graph is Connected using BFS
Extra Login Fields with Spring Security
Java Program to Check Whether an Input Binary Tree is the Sub Tree of the Binary Tree
Java Program to Find Nearest Neighbor Using Linear Search
HttpAsyncClient Tutorial
Iterable to Stream in Java
HashMap trong Java hoạt động như thế nào?
HttpClient Basic Authentication
Guide to @ConfigurationProperties in Spring Boot
Java Program to Implement Interpolation Search Algorithm
Quick Guide to java.lang.System
Extract network card address
Java Web Services – Jersey JAX-RS – REST và sử dụng REST API testing tools với Postman
Guide to Java Instrumentation
Java Program to Implement Self Balancing Binary Search Tree
Java Program to Perform Deletion in a BST
Spring Data MongoDB Transactions
Java Program to Implement Disjoint Sets
Java Program to Find SSSP (Single Source Shortest Path) in DAG (Directed Acyclic Graphs)
Supplier trong Java 8
Sắp xếp trong Java 8
Guide to java.util.concurrent.Locks
Java Program to Implement Horner Algorithm
“Stream has already been operated upon or closed” Exception in Java
Java Program to Find the Minimum Element of a Rotated Sorted Array using Binary Search approach
Java Program to Find the Longest Subsequence Common to All Sequences in a Set of Sequences
Một số từ khóa trong Java
An Intro to Spring Cloud Contract
Java Program to Perform Postorder Recursive Traversal of a Given Binary Tree