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:

Count Occurrences of a Char in a String
Java Program to Evaluate an Expression using Stacks
Java Program to Solve a Matching Problem for a Given Specific Case
Build a REST API with Spring and Java Config
Giới thiệu Google Guice – Dependency injection (DI) framework
Basic Authentication with the RestTemplate
HttpClient Connection Management
Java Program to Implement Stack
Removing Elements from Java Collections
Java Program to Implement TreeMap API
Java Multi-line String
Apache Commons Collections BidiMap
The XOR Operator in Java
Java Program to Find the Longest Subsequence Common to All Sequences in a Set of Sequences
Recommended Package Structure of a Spring Boot Project
Cơ chế Upcasting và Downcasting trong java
Java Program to Implement Patricia Trie
Spring Data MongoDB Transactions
Tạo ứng dụng Java RESTful Client với thư viện Retrofit
Java List UnsupportedOperationException
Java Program to Perform Right Rotation on a Binary Search Tree
Reactive Flow with MongoDB, Kotlin, and Spring WebFlux
Spring Webflux with Kotlin
Mảng (Array) trong Java
Java Program to Check Whether it is Weakly Connected or Strongly Connected for a Directed Graph
Introduction to Using Thymeleaf in Spring
Introduction to the Java NIO2 File API
Introduction to Spring Method Security
OAuth2 for a Spring REST API – Handle the Refresh Token in AngularJS
Custom Thread Pools In Java 8 Parallel Streams
Java Program to Create a Minimal Set of All Edges Whose Addition will Convert it to a Strongly Conne...
Guide to PriorityBlockingQueue in Java