How do you handle session management in Spring Boot in the context of security?

Session management in Spring Boot security governs how a user's authenticated state is tracked across requests, ranging from fully stateless token-based APIs to traditional server-side sessions with configurable lifecycle rules.

Key Points: • By default, Spring Security can be configured stateless (SessionCreationPolicy.STATELESS) for REST APIs that authenticate via JWT on every request. • For web apps, sessions are created on login and tracked via a JSESSIONID cookie. • Session fixation protection regenerates the session ID on login to prevent session hijacking. • maximumSessions() controls how many concurrent sessions a single user may hold, with options to block new logins or expire old sessions. • Session timeouts can be configured to automatically invalidate idle sessions after a set period.

Example: A REST API for mobile clients sets SessionCreationPolicy.STATELESS since JWTs carry all needed auth info, while an internal admin web console keeps default session-based login with a 30-minute idle timeout.

Code Example:

http
    .sessionManagement(session -> session
        .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
        .maximumSessions(1)
        .maxSessionsPreventsLogin(true));

Interview Tip: A concise interview answer is:

"Spring Security supports both stateless and session-based models. For REST APIs I set SessionCreationPolicy.STATELESS since tokens carry auth info on every request. For web apps I configure session creation, timeouts, and concurrent session limits through the sessionManagement DSL to control how many active sessions a user can hold."