Session Management in Spring Security

A session is the server-side record that keeps a user logged in between requests, identified by the JSESSIONID cookie. Session management controls how that session is created, how long it lives, and how many a user may have at once. Spring Security tracks sessions in a SessionRegistry and ends them on logout, timeout or a second login. It is used so idle sessions close automatically and one account cannot be shared across many devices.

Features

  • Idle session timeout, set in application.properties
  • Concurrent login control (maximum sessions per user)
  • Two modes for a second login: end the old session, or reject the new login
  • Session fixation protection (a new session id after login)
  • Redirect URLs for timed-out and expired sessions
  • Logout that invalidates the session and deletes the cookie
  • A SessionRegistry to list active sessions, and to log a user out of other devices
  • Admin control to force a user out

Session Management Types

  • Session Timeout (used here): The session ends after a period of inactivity. This is set with server.servlet.session.timeout, here 2 minutes.
  • Concurrent Session Control (used here): maximumSessions(1) limits each user to one session. With maxSessionsPreventsLogin(false) the new login ends the old session. With true the new login is rejected instead.
  • Session Fixation Protection (used here): After login the session id is changed so an attacker cannot reuse an id they planted. The options are changeSessionId() (used), migrateSession(), newSession() and none().
  • Session Creation Policy: ALWAYS, IF_REQUIRED (default), NEVER or STATELESS decide when Spring Security creates a session. STATELESS is for token-based APIs. It is not changed in this example.

Hands-on Experiment: Building a Corporate Employee Self-Service Portal with Session Management

Aim: To build a Spring Boot application that controls session timeout, concurrent logins and session expiry for employee logins.

Software/Tools Required: JDK 17, Spring Boot 3.x, Maven, MySQL 8.x, IDE (IntelliJ/Eclipse/VS Code), Postman

Step-by-Step Application Development

Step 1: Generate the Project via Spring Initializr

  • Project: Maven | Language: Java | Spring Boot: 3.3.x
  • Group: com.example | Artifact: portal-session | Packaging: Jar | Java: 17
  • Dependencies: Spring Web, Spring Security, Spring Data JPA, MySQL Driver

Step 2: Project Structure

portal-session
├── pom.xml
└── src/main
    ├── java/com/example/portalsession
    │   ├── PortalSessionApplication.java
    │   ├── entity/Employee.java
    │   ├── repository/EmployeeRepository.java
    │   ├── service/EmployeeService.java
    │   ├── service/SessionService.java
    │   ├── service/SecurityConfig.java
    │   ├── controller/PortalController.java
    │   └── controller/SessionController.java
    └── resources/application.properties

Step 3: Create the files according to the project structure

package com.example.portalsession.entity;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "employee")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String fullName;

    @Column(nullable = false, unique = true)
    private String username;

    @Column(nullable = false)
    private String password;

    // EMPLOYEE or ADMIN
    @Column(nullable = false)
    private String role;

    private String department;

    private int leaveBalance;

    public Employee() {
    }

    public Employee(String fullName, String username, String password, String role,
                    String department, int leaveBalance) {
        this.fullName = fullName;
        this.username = username;
        this.password = password;
        this.role = role;
        this.department = department;
        this.leaveBalance = leaveBalance;
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getFullName() { return fullName; }
    public void setFullName(String fullName) { this.fullName = fullName; }

    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }

    public String getPassword() { return password; }
    public void setPassword(String password) { this.password = password; }

    public String getRole() { return role; }
    public void setRole(String role) { this.role = role; }

    public String getDepartment() { return department; }
    public void setDepartment(String department) { this.department = department; }

    public int getLeaveBalance() { return leaveBalance; }
    public void setLeaveBalance(int leaveBalance) { this.leaveBalance = leaveBalance; }
}
package com.example.portalsession.repository;

import com.example.portalsession.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface EmployeeRepository extends JpaRepository<Employee, Long> {

    Optional<Employee> findByUsername(String username);

    boolean existsByUsername(String username);
}
package com.example.portalsession.service;

import com.example.portalsession.entity.Employee;
import com.example.portalsession.repository.EmployeeRepository;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class EmployeeService implements UserDetailsService {

    private final EmployeeRepository repository;
    private final PasswordEncoder passwordEncoder;

    public EmployeeService(EmployeeRepository repository, PasswordEncoder passwordEncoder) {
        this.repository = repository;
        this.passwordEncoder = passwordEncoder;
    }

    // The User object returned here becomes the principal that the session registry tracks
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Employee employee = repository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("Employee not found: " + username));

        return User.builder()
                .username(employee.getUsername())
                .password(employee.getPassword())
                .roles(employee.getRole())
                .build();
    }

    public Employee findByUsername(String username) {
        return repository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("Employee not found: " + username));
    }

    public void createDefaultEmployees() {
        seed("John Carter", "john", "john123", "EMPLOYEE", "Engineering", 12);
        seed("Priya Nair", "priya", "priya123", "EMPLOYEE", "HR", 9);
        seed("Portal Admin", "admin", "admin123", "ADMIN", "IT", 15);
    }

    private void seed(String fullName, String username, String password, String role,
                      String department, int leaveBalance) {
        if (!repository.existsByUsername(username)) {
            repository.save(new Employee(fullName, username, passwordEncoder.encode(password),
                    role, department, leaveBalance));
        }
    }
}
package com.example.portalsession.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.session.HttpSessionEventPublisher;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // Keeps the list of active sessions of every user
    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

    // Tells the registry when a session ends (logout or timeout), otherwise it keeps dead sessions
    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http,
            SessionRegistry sessionRegistry,
            @Value("${app.session.max-per-user}") int maxSessions,
            @Value("${app.session.prevent-login}") boolean preventLogin) throws Exception {

        http
            .csrf(csrf -> csrf.disable())   // so the URLs can be tested from Postman
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/login", "/session-invalid", "/session-expired").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .formLogin(form -> form
                .defaultSuccessUrl("/api/profile", true)
                .failureUrl("/login?error")
                .permitAll())
            .logout(logout -> logout
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login?logout")
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID")
                .permitAll())
            .sessionManagement(session -> {
                // request carries a timed-out or unknown session id
                session.invalidSessionUrl("/session-invalid");
                // new session id after login (protects against session fixation)
                session.sessionFixation(fixation -> fixation.changeSessionId());
                // concurrent login control
                session.maximumSessions(maxSessions)
                       .maxSessionsPreventsLogin(preventLogin)
                       .expiredUrl("/session-expired")     // where an expired session is sent
                       .sessionRegistry(sessionRegistry);
            });

        return http.build();
    }
}
package com.example.portalsession.service;

import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Works on top of the SessionRegistry, which knows every active login session.
 */
@Service
public class SessionService {

    private final SessionRegistry sessionRegistry;

    public SessionService(SessionRegistry sessionRegistry) {
        this.sessionRegistry = sessionRegistry;
    }

    public List<Map<String, Object>> getActiveSessions(String username) {
        List<Map<String, Object>> result = new ArrayList<>();
        for (Object principal : sessionRegistry.getAllPrincipals()) {
            if (principal instanceof UserDetails user && user.getUsername().equals(username)) {
                for (SessionInformation info : sessionRegistry.getAllSessions(principal, false)) {
                    result.add(toMap(user.getUsername(), info));
                }
            }
        }
        return result;
    }

    public List<Map<String, Object>> getAllActiveSessions() {
        List<Map<String, Object>> result = new ArrayList<>();
        for (Object principal : sessionRegistry.getAllPrincipals()) {
            if (principal instanceof UserDetails user) {
                for (SessionInformation info : sessionRegistry.getAllSessions(principal, false)) {
                    result.add(toMap(user.getUsername(), info));
                }
            }
        }
        return result;
    }

    // "Log out from all other devices"
    public int expireOtherSessions(String username, String currentSessionId) {
        int count = 0;
        for (Object principal : sessionRegistry.getAllPrincipals()) {
            if (principal instanceof UserDetails user && user.getUsername().equals(username)) {
                for (SessionInformation info : sessionRegistry.getAllSessions(principal, false)) {
                    if (!info.getSessionId().equals(currentSessionId)) {
                        info.expireNow();
                        count++;
                    }
                }
            }
        }
        return count;
    }

    // Admin: force every session of one user to end
    public int expireAllSessions(String username) {
        return expireOtherSessions(username, "");
    }

    private Map<String, Object> toMap(String username, SessionInformation info) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("username", username);
        map.put("sessionId", info.getSessionId());
        map.put("lastRequest", info.getLastRequest().toInstant().toString());
        map.put("expired", info.isExpired());
        return map;
    }
}
package com.example.portalsession.controller;

import com.example.portalsession.entity.Employee;
import com.example.portalsession.service.EmployeeService;
import jakarta.servlet.http.HttpSession;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
public class PortalController {

    private final EmployeeService employeeService;

    public PortalController(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    // Self-service page: employee details plus the details of the current session
    @GetMapping("/api/profile")
    public Map<String, Object> profile(Authentication authentication, HttpSession session) {
        Employee employee = employeeService.findByUsername(authentication.getName());

        Map<String, Object> profile = new LinkedHashMap<>();
        profile.put("fullName", employee.getFullName());
        profile.put("username", employee.getUsername());
        profile.put("department", employee.getDepartment());
        profile.put("role", employee.getRole());
        profile.put("leaveBalance", employee.getLeaveBalance());
        profile.put("sessionId", session.getId());
        profile.put("sessionCreated", Instant.ofEpochMilli(session.getCreationTime()).toString());
        profile.put("lastAccessed", Instant.ofEpochMilli(session.getLastAccessedTime()).toString());
        profile.put("timeoutSeconds", session.getMaxInactiveInterval());
        return profile;
    }

    // Idle timeout: the session id sent by the client is no longer valid
    @GetMapping("/session-invalid")
    public ResponseEntity<Map<String, String>> sessionInvalid() {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(Map.of("error", "Session timed out or is invalid. Please login again"));
    }

    // Concurrent login: this session was ended because the same user logged in elsewhere
    // (or an admin or the user ended it)
    @GetMapping("/session-expired")
    public ResponseEntity<Map<String, String>> sessionExpired() {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(Map.of("error", "Session expired because it was ended from another login. Please login again"));
    }
}
package com.example.portalsession.controller;

import com.example.portalsession.service.SessionService;
import jakarta.servlet.http.HttpSession;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class SessionController {

    private final SessionService sessionService;

    public SessionController(SessionService sessionService) {
        this.sessionService = sessionService;
    }

    // My active login sessions
    @GetMapping("/api/sessions/my")
    public List<Map<String, Object>> mySessions(Authentication authentication) {
        return sessionService.getActiveSessions(authentication.getName());
    }

    // Log out from all other devices (the current session stays)
    @PostMapping("/api/sessions/logout-others")
    public Map<String, Object> logoutOthers(Authentication authentication, HttpSession session) {
        int ended = sessionService.expireOtherSessions(authentication.getName(), session.getId());
        return Map.of("message", "Other sessions ended", "count", ended);
    }

    // ADMIN: every active session of every user
    @GetMapping("/api/admin/sessions")
    public List<Map<String, Object>> allSessions() {
        return sessionService.getAllActiveSessions();
    }

    // ADMIN: force a user out
    @PostMapping("/api/admin/sessions/{username}/expire")
    public Map<String, Object> expireUser(@PathVariable String username) {
        int ended = sessionService.expireAllSessions(username);
        return Map.of("message", "Sessions ended for " + username, "count", ended);
    }
}
package com.example.portalsession;

import com.example.portalsession.service.EmployeeService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class PortalSessionApplication {

    public static void main(String[] args) {
        SpringApplication.run(PortalSessionApplication.class, args);
    }

    // Creates demo employees on first start
    @Bean
    CommandLineRunner seedEmployees(EmployeeService service) {
        return args -> service.createDefaultEmployees();
    }
}
spring.application.name=portal-session
server.port=8080

# MySQL (database is created automatically if missing)
spring.datasource.url=jdbc:mysql://localhost:3306/portal_db?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

# Session timeout: an idle session expires after 2 minutes (short, so it is easy to test)
server.servlet.session.timeout=2m
server.servlet.session.cookie.http-only=true

# Concurrent login control
app.session.max-per-user=1
# false = a new login expires the old session, true = a new login is rejected
app.session.prevent-login=falseCode language: PHP (php)

Step 4: Run the PortalSessionApplication

URLs and Payloads

This project has no JSON POST body. Login is a form POST, and the other POST calls send no body.

Logins: john / john123 (EMPLOYEE), priya / priya123 (EMPLOYEE), admin / admin123 (ADMIN)

Scroll to Top