Spring Boot Session Timeout Redirect To Login Page

Minimizing session timeouts is a common challenge for developers when working with web applications. In this article, I will discuss how we can set up Spring Boot to automatically redirect users to the login page once their session ends.

Understanding Session Timeout

Session timeout refers to the duration for which a user session remains active after their last request. The session timeout is typically set in the web application’s configuration file, and once the timeout is reached, the user is logged out and redirected to the login page.

Configuring Session Timeout in Spring Boot

In a Spring Boot application, we can configure the session timeout using the server.servlet.session.timeout property. This property specifies the session timeout in seconds. By default, the session timeout is set to 1800 seconds (30 minutes).

Let’s say we want to set the session timeout to 900 seconds (15 minutes). We can add the following line to our application.properties file:

server.servlet.session.timeout=900

Alternatively, we can set the session timeout programmatically by creating a SessionListener bean and overriding the sessionCreated method:

@Bean
public HttpSessionListener httpSessionListener() {
    return new SessionListener();
}

private class SessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent event) {
        event.getSession().setMaxInactiveInterval(900);
    }
}

Redirecting to the Login Page

Once the session timeout is reached, we need to redirect the user to the login page. This can be done by implementing a custom InvalidSessionStrategy.

public class CustomInvalidSessionStrategy implements InvalidSessionStrategy {
    private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException {
        redirectStrategy.sendRedirect(request, response, "/login");
    }
}

To configure Spring Boot to use our custom invalid session strategy, we need to create a bean of type InvalidSessionStrategy:

@Bean
public InvalidSessionStrategy invalidSessionStrategy() {
    return new CustomInvalidSessionStrategy();
}

Conclusion

In this article, we explored how to configure Spring Boot to redirect users to the login page when their session expires. We learned how to set the session timeout and implement a custom invalid session strategy. By properly managing session timeouts, we can enhance the security and user experience of our web applications.

Feel free to experiment with different session timeout values and customize the redirect strategy according to your application’s requirements. Happy coding!