Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 41

Secure Server-Side Logout for Refresh Tokens

This lesson is built with resources from youtube.com, medium.com and 1 more site.

Hello! Welcome to the final lesson of our module on production-grade API security.

In our last session, we built a robust token refresh mechanism. Our users can now enjoy seamless sessions, with short-lived access tokens being renewed automatically using a long-lived refresh token stored securely in an HttpOnly cookie.

However, our authentication flow is still missing a critical piece: a secure logout. Today, we will address the learning outcome: Build a logout mechanism that invalidates the refresh token on the server-side. Simply deleting the token on the client isn't enough; we need to ensure that even if a refresh token is compromised, it becomes useless the moment a user logs out.

The Challenge of Stateless Logout

In a traditional session-based system, logging out is simple: the server destroys the session. With stateless JWTs, there is no "session" on the server to destroy. A JWT is valid until it expires. This is why we must implement a server-side invalidation strategy. Since we are already persisting our refresh tokens in the database, our strategy is straightforward: when a user logs out, we will delete their refresh token from our database, effectively "blacklisting" it.

Invalidate/Blacklist the JWT using Redis: Logout Mechanism in Spring Security
This diagram shows a common pattern for JWT invalidation. While it uses Redis, the concept is the same for our PostgreSQL database. Upon logout, the token is added to a "blacklist" (or in our case, deleted from the list of valid tokens). The `JwtAuthFilter` then checks this list for every request, ensuring invalidated tokens are rejected.

MERN-to-Spring Mapping: Logout Middleware

In a MERN application, you would create a /logout route. The handler for this route would likely receive the refresh token, delete it from your database (e.g., MongoDB or a Redis cache), and then clear the client-side cookie using res.clearCookie('refreshToken').

In Spring, the pattern is analogous but more structured. We'll create a custom LogoutHandler—the equivalent of your Express middleware—and wire it into Spring Security's filter chain. This handler will contain the logic to delete the token from our PostgreSQL database.


1. The Strategy: A Custom Logout Handler

Spring Security provides a powerful and extensible logout mechanism centered around the LogoutHandler interface. We will create a custom implementation that hooks into the logout process to perform our application-specific cleanup.

Let's watch a video that explains the core concepts behind this approach.

JWT Logout: The Trick You Missed in Spring Security (Solved!)

The video 'JWT Logout: The Trick You Missed in Spring Security' by Learn With Ifte provides an excellent conceptual overview of why JWT logout is tricky and how to solve it by introducing a server-side token store and a custom logout handler. It explains the exact pattern we're about to implement.

Please watch from the beginning to 05:36 to understand the difference between session-based and JWT authentication and why we need a server-side token store. Then, watch from 19:25 to 21:35 to see how a custom LogoutHandler is implemented and configured to find the token and mark it as invalid in the database. The video uses an is_logged_out flag, but our implementation will delete the token, which is a similar invalidation strategy.


2. Implementing the CustomLogoutHandler

Now, let's write the code. Our handler needs to do one thing: find the refresh token from the incoming request's cookie and delete it from the database.

Create a new class CustomLogoutHandler in the config package.

// src/main/java/com/example/blogplatform/config/CustomLogoutHandler.java
package com.example.blogplatform.config;

import com.example.blogplatform.repository.RefreshTokenRepository;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@RequiredArgsConstructor
@Slf4j
public class CustomLogoutHandler implements LogoutHandler {

    private final RefreshTokenRepository refreshTokenRepository;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        // 1. Extract the refresh token from the cookie
        String refreshToken = null;
        if (request.getCookies() != null) {
            refreshToken = Arrays.stream(request.getCookies())
                    .filter(cookie -> "refreshToken".equals(cookie.getName()))
                    .map(Cookie::getValue)
                    .findFirst()
                    .orElse(null);
        }

        if (refreshToken == null) {
            log.warn("Logout attempt without a refresh token cookie.");
            return;
        }

        // 2. Find and delete the token from the database
        refreshTokenRepository.findByToken(refreshToken)
                .ifPresent(token -> {
                    log.info("Logging out user. Deleting refresh token: {}", token.getToken());
                    refreshTokenRepository.delete(token);
                });
    }
}

Code Breakdown:

  • We implement the LogoutHandler interface.
  • We inject our RefreshTokenRepository to interact with the database.
  • In the logout method, we find the refreshToken cookie.
  • If the cookie exists, we use its value to find the corresponding RefreshToken entity in our database and delete it. ifPresent() is a clean way to execute code only if the Optional contains a value.

3. Configuring the Security Filter Chain

Now we need to tell Spring Security to use our CustomLogoutHandler and to configure the logout endpoint. For this, we'll turn to the official documentation for the correct DSL usage.

Handling Logouts :: Spring Security

The official Spring Security documentation, 'Handling Logouts', is the definitive source for configuring this feature. It explains how to add custom handlers and manage cookies during logout.

First, read the subsection 'Understanding Logout’s Architecture' to see what Spring Security does by default during logout. Then, focus on the section 'Adding Clean-up Actions'. This section shows the .addLogoutHandler() method, which is exactly what we need, and also introduces the convenient .deleteCookies() method for cleaning up the client's browser.

Armed with this knowledge, let's update our SecurityConfig.

// src/main/java/com/example/blogplatform/config/SecurityConfig.java

// ... other imports
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtAuthenticationFilter jwtAuthFilter;
    private final AuthenticationProvider authenticationProvider;
    // Inject our custom handler
    private final LogoutHandler logoutHandler; 

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(req -> req
                        .requestMatchers("/api/v1/auth/**")
                        .permitAll()
                        .requestMatchers("/api/v1/admin/**").hasRole("ADMIN")
                        .anyRequest()
                        .authenticated()
                )
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authenticationProvider(authenticationProvider)
                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
                // Add the logout configuration
                .logout(logout -> logout
                        .logoutUrl("/api/v1/auth/logout")
                        .addLogoutHandler(logoutHandler)
                        .logoutSuccessHandler(((request, response, authentication) -> SecurityContextHolder.clearContext()))
                );

        return http.build();
    }
}

Configuration Breakdown:

  • We inject our CustomLogoutHandler (which Spring knows about because of the @Component annotation).
  • .logoutUrl("/api/v1/auth/logout"): This defines the endpoint that will trigger the logout process.
  • .addLogoutHandler(logoutHandler): This registers our custom handler. It will be executed as part of the logout process.
  • .logoutSuccessHandler(...): By default, Spring redirects to /login?logout. For a stateless API, we don't want a redirect. Instead, we provide a simple handler that clears the server's security context and implicitly returns a 200 OK status, which is perfect for an API.

What about the client-side cookie?
Our CustomLogoutHandler only deals with the server side. To instruct the browser to delete its refreshToken cookie, we would typically send a Set-Cookie header with Max-Age=0. While you could do this manually in the logoutSuccessHandler, Spring Security's default SecurityContextLogoutHandler (which runs automatically) also invalidates the session, and if you use cookies for sessions, it can clear them. However, since ours is a custom cookie, we should manage it. A better approach is to create a dedicated LogoutSuccessHandler that does both clearing the context and the cookie.

Let's refine our configuration for a more robust solution. We'll create a success handler that sends back a simple message and also clears the cookie.

First, let's create a utility in our CookieService (if you created one previously) or as a static method to generate the cookie clearing header.

Let's create a dedicated success handler for clarity.

// In a new file or inside SecurityConfig as a private class
// src/main/java/com/example/blogplatform/config/CustomLogoutSuccessHandler.java

package com.example.blogplatform.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import java.io.IOException;

@Component
public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        // Clear the refresh token cookie
        String cookieHeader = String.format("refreshToken=; Max-Age=0; Path=/; HttpOnly; Secure; SameSite=Strict");
        response.addHeader("Set-Cookie", cookieHeader);
        
        // Send a simple success response
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().flush();
        
        // Clear the context
        SecurityContextHolder.clearContext();
    }
}

Now, inject and use this in SecurityConfig:

// src/main/java/com/example/blogplatform/config/SecurityConfig.java

// ...
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; // new import

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtAuthenticationFilter jwtAuthFilter;
    private final AuthenticationProvider authenticationProvider;
    private final LogoutHandler logoutHandler;
    // Inject our new success handler
    private final LogoutSuccessHandler logoutSuccessHandler; 

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // ... (csrf, authorizeHttpRequests, etc.)
                .logout(logout -> logout
                        .logoutUrl("/api/v1/auth/logout")
                        .addLogoutHandler(logoutHandler)
                        // Use the dedicated success handler
                        .logoutSuccessHandler(logoutSuccessHandler) 
                );

        return http.build();
    }
}

4. Runtime Observation & Debugging Task

It's time to see our work in action.

  1. Restart your application.
  2. Set a breakpoint inside the logout method of your CustomLogoutHandler.
  3. Using Postman, log in by sending a POST request to /api/v1/auth/login. Confirm you receive an access token and a refreshToken cookie.
  4. Use the /api/v1/auth/refresh endpoint to confirm your refresh token works and you can get a new access token.
  5. Now, send a POST request to /api/v1/auth/logout.
    • Observe: Your breakpoint in CustomLogoutHandler should be hit.
    • Inspect: Examine the request object. You'll find the refreshToken cookie.
    • Step through: Watch as the code finds the token in the database and then deletes it. You can verify this by checking your refresh_token table in your database client before and after this step.
  6. Let the request complete. In Postman, check the response. It should be a 200 OK. In the Headers tab, you should see a Set-Cookie header for refreshToken with Max-Age=0.
  7. Final Verification: Try to use the /api/v1/auth/refresh endpoint again.
    • Observe: The request should now fail! Your CustomLogoutHandler correctly deleted the token from the database, so the refresh endpoint can no longer find it. You should get the RuntimeException: Refresh token is not in database! we wrote in the previous lesson.

You have now successfully built a truly secure logout mechanism!


Conclusion

This lesson completes our authentication module. We have built a system that is not only secure against common attacks like XSS (by using HttpOnly cookies) but also provides a great user experience (with refresh tokens) and, critically, ensures sessions can be properly terminated (with server-side invalidation).

Key Takeaways:

  • Stateless Logout Requires Server-Side Invalidation: A JWT cannot be "un-issued." To log a user out, you must invalidate their tokens on the server.
  • The LogoutHandler Pattern: Spring Security provides the LogoutHandler interface as the standard, clean way to inject custom cleanup logic into the logout process.
  • Complete Logout: A full logout involves both server-side invalidation (deleting the token from the DB) and client-side cleanup (clearing the cookie).
  • API-friendly Logout: For a REST API, a successful logout should typically return a 200 OK status, not a redirect.

Preview of the Next Module:

Congratulations on building a complete, production-grade authentication service! You've mastered the core of securing a modern Spring Boot application.

In the next module, we'll pivot from synchronous request-response communication to a new, powerful paradigm: Event-Driven Architecture with Apache Kafka. We will start by setting up Kafka locally and implementing our first asynchronous flow, where a UserRegistered event is published by our Auth service, opening the door to building loosely coupled, scalable microservices.