Video in progress

Strong Middle 🌱 Spring

A user should be logged in from only one device at a time. How do you limit the number of sessions in Spring Security?

Inside sessionManagement you set maximumSessions(1) and register an HttpSessionEventPublisher bean, and Spring Security tracks each user's sessions in a SessionRegistry. With several instances the registry has to be shared too, which means Spring Session (Redis or JDBC).

📖 Answer

@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(a -> a.anyRequest().authenticated())
        .formLogin(Customizer.withDefaults())
        .sessionManagement(s -> s
            .maximumSessions(1)
            .maxSessionsPreventsLogin(false)   // a new login kicks the old session out
            .expiredUrl("/login?expired"));
    return http.build();
}

@Bean
HttpSessionEventPublisher httpSessionEventPublisher() {
    return new HttpSessionEventPublisher();   // so the registry learns when a session ends
}

maxSessionsPreventsLogin gives you two different policies. With false the last login wins: the next request from the old device lands on expiredUrl. With true the second login is rejected. The second one produces a lot of complaints: the browser was closed, but the session is still alive on the server, so the user can't log in until the timeout runs out.

Without HttpSessionEventPublisher, sessions that end without a logout are never removed from the registry, and in true mode a user can get locked out completely.

This is where people often slip in interviews: the cluster. The default SessionRegistryImpl lives in memory. With 3 instances each one knows only its own sessions, so the limit effectively does nothing. The fix is Spring Session and its registry:

@Bean
SpringSessionBackedSessionRegistry<?> sessionRegistry(FindByIndexNameSessionRepository<?> repo) {
    return new SpringSessionBackedSessionRegistry<>(repo);
}

then .maximumSessions(1).sessionRegistry(sessionRegistry).

This mechanism doesn't work at all in a stateless JWT API. There, the "one device" rule is built by storing refresh tokens on the server and revoking the old ones on each new login. The access token still stays alive for a short while anyway.