Search code examples
javaspring-mvcsessiontomcatspring-security

Persist sessions with Spring security after restart without database/cache


I use Spring Boot 3.2.5 with MVC and Spring Security. Currently, users have to login again if the application has restarted.

As far as I read Tomcat has the ability to persist sessions by setting

server.servlet.session.persistent=true

in the application.properties.

For testing, I made a simple app (see below). However, it is not working. If I additionally set

server.servlet.session.store-dir=sessions

then the folder sessions is created after I stop the application, but it is empty. The user still has to log in again.

What am I doing wrong, or is it not possible?

application.properties:

server.servlet.session.persistent=true
server.servlet.session.store-dir=sessions

AppController:

@Controller
public class AppController {
    @GetMapping("/")
    @ResponseBody
    public String index() {
        return "logged in";
    }
}

AppConfiguration:

@Configuration
public class AppConfiguration
{
    @Bean
    public UserDetailsService users() {
        var admin = User.withDefaultPasswordEncoder()
            .username("admin").password("password").roles("USER", "ADMIN").build();
        return new InMemoryUserDetailsManager(admin);
    }
}

Solution

  • The setting is working correctly. The problem was, that the application was stopped with a SIGKILL signal by the IDE. For the context to gracefully stop, SIGTERM is needed. With SIGTERM, the sessions are correctly persisted to the disk and everything is working.