Skip to content
notes.vinhnq.com

Search

SecuritySenior18 min read

Sessions and remember-me in Spring: Spring Session JDBC, session limits and three ways to stay logged in

Review 15 cards
On this page

Spring MVC end to end series: 1. Maven and project layout · 2. DispatcherServlet and views · 3. Forms and validation · 4. Form login with Spring Security · 5. Sessions and remember-me · 6. File upload · 7. Cart and checkout · 8. Pagination and dynamic filters

After part 4 users can log in; this post is about keeping them logged in: where the session lives, how long it lasts, how many devices at once, and how “remember me” works. Afterwards you can move sessions out of Tomcat’s memory with Spring Session JDBC, pick the right remember-me style, and avoid serialization errors when storing objects in the session. Cookie theory, the HttpOnly/SameSite flags and sessions versus JWT are in authentication with session cookies and JWT.

At a glance:

sequenceDiagram
  participant B as Browser
  participant S as Application
  participant K as Shared session store
  B->>S: Log in
  S->>S: changeSessionId
  S->>K: Save SecurityContext
  S-->>B: Cookie holds only session id
  B->>S: Request with cookie
  S->>K: Load session by id
  Note over S,K: Attributes must be serializable
  B->>S: Session expired, remember-me left
  S-->>B: Logged in again automatically

1. What Spring Security keeps in the session

Key idea: the browser only holds a JSESSIONID cookie (or SESSION with Spring Session) carrying a random id. Everything else lives in the session on the server.

After a login in the lab, the session has these attributes:

Attribute Written by Purpose
SPRING_SECURITY_CONTEXT SecurityContextRepository holds the Authentication (principal, authorities)
SPRING_SECURITY_SAVED_REQUEST ExceptionTranslationFilter the URL requested before the login redirect
CSRF token HttpSessionCsrfTokenRepository compared with the token in the form
application attributes your code e.g. a guest’s temporary cart

A session is created when needed (SessionCreationPolicy.IF_REQUIRED, the default). The course material sets ALWAYS: unnecessary, and it makes every passing visitor (and every bot) create a session row in the database.

To get user details in a controller, use @AuthenticationPrincipal ShopUserDetails me (read from the SecurityContext) rather than copying name, avatar and id into separate session attributes as the course does. Copies mean two sources of truth: change your name on the profile page and the header still shows the old one.

2. Session fixation and changing the id on login

Key idea: on successful login Spring Security issues a new session id and keeps the data. An attacker who planted an old id in the victim’s browser can’t use it.

The attack itself is in the authentication post, section 3. The four sessionFixation() options:

  • changeSessionId() (default): calls Servlet 3.1’s HttpServletRequest.changeSessionId(), keeping attributes.
  • migrateSession(): creates a new session and copies attributes over.
  • newSession(): new session, nothing copied (the saved request is lost).
  • none(): changes nothing; don’t use it.

The lab’s sessionIdChangesOnLogin test: the SESSION cookie before and after POST /login differ, even with the session stored in the database.

3. Timeouts: idle, absolute and closing the browser

Key idea: an idle timeout (expire after a period of inactivity) is built in; an absolute timeout (a maximum lifetime even when active) is not. Closing the browser is not a security mechanism.

  • Without Spring Session: server.servlet.session.timeout=30m (Tomcat rounds to minutes).
  • With Spring Session: spring.session.timeout=30m; if unset, it falls back to server.servlet.session.timeout. The lab sets 30 minutes and the test reads MAX_INACTIVE_INTERVAL = 1800 from the table.
  • An absolute timeout (12 hours, say) is your own code: a filter compares session.getCreationTime() with the limit and calls invalidate().

Two URLs that get confused: invalidSessionUrl is used when the browser sends a session id that has expired or doesn’t exist; expiredUrl is used when a session was kicked out for exceeding the session limit (section 4).

4. Limiting concurrent sessions

Key idea: maximumSessions(1) allows one session per account. It needs a SessionRegistry that knows every live session; with several instances the registry must read from the shared session store.

.sessionManagement(s -> s
    .sessionFixation(f -> f.changeSessionId())
    .maximumSessions(1)
    .maxSessionsPreventsLogin(false)     // default: a new login kicks out the old session
    .sessionRegistry(registry)           // SpringSessionBackedSessionRegistry
    .expiredUrl("/login?expired"))
maxSessionsPreventsLogin Second login Consequence
false (default) succeeds, old session marked expired the old session is kicked out on its next request
true rejected, goes to failureUrl forget to log out at work and you can’t log in at home until the timeout

Test secondLoginExpiresFirstSession: Alice logs in once and can open /cart; she logs in again; the next request with the old cookie is redirected to /login?expired. The kick-out is lazy: ConcurrentSessionFilter only checks when the old session sends a request.

5. Spring Session: moving the session out of Tomcat

Key idea: Spring Session puts a filter (SessionRepositoryFilter) in front of everything else and wraps the request, so request.getSession() returns a session read from Redis or a database. Your code and Spring Security don’t change.

Adding spring-session-jdbc is enough; Spring Boot 3 detects the single store on the classpath.

spring.session.timeout=30m
spring.session.jdbc.initialize-schema=embedded   # creates tables for H2; real MySQL: create them with Flyway
# spring.session.jdbc.cleanup-cron=0 * * * * *   # default: delete expired sessions every minute
  • Tables: SPRING_SESSION (id, CREATION_TIME, LAST_ACCESS_TIME, MAX_INACTIVE_INTERVAL, EXPIRY_TIME, PRINCIPAL_NAME) and SPRING_SESSION_ATTRIBUTES (attribute name, value as bytes).
  • Cookie: called SESSION instead of JSESSIONID, its value is the base64-encoded id.
  • Cleanup: a cron job deletes expired rows; Tomcat no longer does it.
  • Server restart: sessions survive, because they’re in the database.
Store Pros Cons
Tomcat RAM (default) nothing extra, fastest lost on restart, not shared between instances
JDBC uses the existing database, easy to query and back up each request may write LAST_ACCESS_TIME, extra load on the main DB
Redis fast (under 1 ms), TTL expires keys one more system to operate

A detailed comparison of Redis sessions versus JWT: the authentication post, section 3.2.

Reducing the write load of Spring Session JDBC
  • Every request that reads the session updates LAST_ACCESS_TIME. A page with 20 static asset requests going through the filter means 20 writes; serve static assets from a CDN or keep them out of session scope.
  • spring.session.jdbc.flush-mode=on-save (default) writes at the end of the request; immediate writes on every setAttribute.
  • spring.session.jdbc.save-mode=on-set-attribute (default) only writes attributes passed to setAttribute; mutating an object from getAttribute without setting it again is not saved. always writes every attribute that was read: safer, but costlier.
  • Indexes on EXPIRY_TIME (cleanup job) and PRINCIPAL_NAME (lookup by user) are in Spring Session’s schema script; if you create the tables with Flyway, don’t forget them.

6. Serialization: why putting an entity in the session breaks

Key idea: once the session lives outside the JVM, every attribute must convert to bytes and back. Only put small, Serializable, rarely changing objects in the session; never JPA entities.

The error the course hits (its “session storing an object” bug-fix lesson) is the textbook case: store a non-Serializable object in the session and Spring Session JDBC throws a SerializationFailedException wrapping NotSerializableException on write. The fix “implement Serializable” works, but three problems remain:

  • An entity drags its whole graph: Hibernate lazy proxies, collections, bidirectional links. The bytes grow, and deserializing on the next request gives an object detached from any persistence context, so touching a lazy field fails.
  • Stale data: prices, stock and names in the session don’t follow the database.
  • Class changes on deploy: old sessions in the DB were serialized with the previous version of the class. Change fields without a compatible serialVersionUID and deserialization throws InvalidClassException, so users get a 500 right after the deploy. During a rolling update the old and new versions read the same session store, so the session format must stay compatible both ways, like the schema (Deployment strategies).

The lab’s principal is a small record, ShopUserDetails(id, email, passwordHash, role); UserDetails already extends Serializable. The cart lives in the database per user (part 7), not in the session.

Storing sessions as JSON instead of Java serialization

Spring Session JDBC uses Java serialization through a ConversionService. Declare a bean named springSessionConversionService to switch to JSON with Jackson, plus Spring Security’s modules so the SecurityContext can be read and written. The snippet follows the Spring Session docs; I haven’t run it in the lab:

@Bean("springSessionConversionService")
GenericConversionService springSessionConversionService(ClassLoader loader) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModules(SecurityJackson2Modules.getModules(loader));
    mapper.addMixIn(ShopUserDetails.class, ShopUserDetailsMixin.class);   // allow our own class
    var converter = new GenericConversionService();
    converter.addConverter(Object.class, byte[].class, new SerializingConverter(new JsonSerializer(mapper)));
    converter.addConverter(byte[].class, Object.class, new DeserializingConverter(new JsonDeserializer(mapper)));
    return converter;
}

Benefits: session data is human-readable, class changes break less often, and you avoid Java deserialization risks (a classic vulnerability if an attacker can write to the session store). The cost: a type allowlist for Jackson and longer configuration. JSON is worth considering by default when you choose Redis.

7. Remember-me: three ways and their costs

Key idea: remember-me keeps a user logged in after the normal session has ended. Spring offers three ways, which differ in whether you can revoke one device and whether a stolen cookie is detected.

Style Cookie contains Revoke one device Detects theft
TokenBasedRememberMeServices username, expiry, a hash signed with the password hash and a key no (only a password or key change, which kills them all) no
PersistentTokenBasedRememberMeServices random series + token, stored in persistent_logins yes: delete the row yes: right series, wrong token
SpringSessionRememberMeServices the SESSION cookie itself, the session lives longer yes: delete the session no

The first two create a new login from the cookie once the old session is gone. Spring marks it as a RememberMeAuthenticationToken, so fullyAuthenticated() can tell “logged in with a password” from “remembered from last week” and ask for the password again before sensitive actions.

The third style (used in the lab) doesn’t log anyone in again: ticking “remember me” raises the session’s own maxInactiveInterval (14 days in the lab) and makes the cookie persistent. Simple and revocable, but it loses that distinction: you must track “last re-authenticated at” yourself if you need to re-ask for the password.

Persistent tokens: detecting a stolen remember-me cookie

Table persistent_logins(username, series, token, last_used). Each password login with the box ticked creates a new series (fixed for that device) and a random token.

  • Each time the cookie is used to log in again, the token rotates: a new token goes into the DB and the cookie, the series stays.
  • If a thief uses the cookie first, the token in the DB changes; the next time the victim uses the old cookie, the series matches but the token doesn’t. Spring throws CookieTheftException and deletes all tokens of that user.
  • Configuration: .rememberMe(r -> r.tokenRepository(jdbcTokenRepository).tokenValiditySeconds(14 * 24 * 3600)) with JdbcTokenRepositoryImpl.

It’s the same idea as rotating refresh tokens (the authentication post, section 6.1).

8. Logging out everywhere

Key idea: because sessions live in a shared store with a PRINCIPAL_NAME column, finding and deleting all of a user’s sessions takes a few lines. Do it on password change, when an admin locks an account, or when the user clicks “log out everywhere”.

@Service
class SessionKiller {
    private final FindByIndexNameSessionRepository<? extends Session> sessions;
    SessionKiller(FindByIndexNameSessionRepository<? extends Session> sessions) { this.sessions = sessions; }

    void logoutEverywhere(String email) {
        sessions.findByPrincipalName(email).keySet().forEach(sessions::deleteById);
    }
}

With persistent-token remember-me, also delete the user’s rows in persistent_logins. The hashed-cookie style can’t revoke one device: changing the password invalidates the old signatures, so every device is logged out together. I haven’t added this snippet to the lab’s tests.

Exercises

Task (the course lab, restated): the app from part 4 loses every login on restart. (1) Move sessions into the database with Spring Session JDBC. (2) A 30-minute idle timeout. (3) One session per account: logging in on a new device pushes the old one out with a message. (4) The “Remember me” box keeps the session for 14 days. (5) Write tests proving each point.

Solution: configuration and tests

Run on Spring Boot 3.5.9, Java 21, in-memory H2, mvn test: the lab’s 23 tests pass (the three relevant ones are below).

@Bean
SpringSessionRememberMeServices rememberMeServices() {
    var s = new SpringSessionRememberMeServices();   // alwaysRemember defaults to false
    s.setValiditySeconds(14 * 24 * 3600);
    return s;
}

@Bean
<S extends Session> SpringSessionBackedSessionRegistry<S> sessionRegistry(FindByIndexNameSessionRepository<S> repo) {
    return new SpringSessionBackedSessionRegistry<>(repo);
}

// inside the SecurityFilterChain
.rememberMe(r -> r.rememberMeServices(rememberMe))
.sessionManagement(s -> s
    .sessionFixation(f -> f.changeSessionId())
    .maximumSessions(1)
    .sessionRegistry(registry)
    .expiredUrl("/login?expired"))
spring.session.timeout=30m
spring.session.jdbc.initialize-schema=embedded
server.servlet.session.cookie.http-only=true
server.servlet.session.cookie.same-site=lax

When Spring Boot sees a SpringSessionRememberMeServices bean it configures the cookie serializer to honour the remember-me flag; no CookieSerializer bean is needed.

@Test void sessionIsStoredInDatabaseAndRememberMeExtendsIt() throws Exception {
    mvc.perform(post("/login").with(csrf()).param("email", "alice@shop.dev").param("password", "password1"))
       .andExpect(cookie().exists("SESSION"));
    Integer normal = jdbc.queryForObject(
        "select max(MAX_INACTIVE_INTERVAL) from SPRING_SESSION where PRINCIPAL_NAME='alice@shop.dev'", Integer.class);
    assertThat(normal).isEqualTo(1800);
    mvc.perform(post("/login").with(csrf()).param("email", "admin@shop.dev").param("password", "password1")
                .param("remember-me", "on"))
       .andExpect(cookie().maxAge("SESSION", Integer.MAX_VALUE));   // "forever" cookie, real expiry held by the server
    Integer remembered = jdbc.queryForObject(
        "select max(MAX_INACTIVE_INTERVAL) from SPRING_SESSION where PRINCIPAL_NAME='admin@shop.dev'", Integer.class);
    assertThat(remembered).isEqualTo(14 * 24 * 3600);
}

@Test void secondLoginExpiresFirstSession() throws Exception {
    Cookie first = mvc.perform(post("/login").with(csrf())
            .param("email", "alice@shop.dev").param("password", "password1"))
        .andReturn().getResponse().getCookie("SESSION");
    mvc.perform(get("/cart").cookie(first)).andExpect(status().isOk());
    mvc.perform(post("/login").with(csrf()).param("email", "alice@shop.dev").param("password", "password1"));
    mvc.perform(get("/cart").cookie(first)).andExpect(redirectedUrl("/login?expired"));
}

The sessionIdChangesOnLogin test is in section 2. Not run: real MySQL (H2 only), Redis, persistent tokens, the JSON serializer, absolute timeout.

What a senior would add:

  • Create the session tables with Flyway (with indexes); never initialize-schema=always in production.
  • A 12-hour absolute timeout via a filter, and a password re-prompt before sensitive actions when the session came from remember-me.
  • “Log out everywhere” on password change; a “devices logged in” page built from findByPrincipalName.
  • A __Host-SESSION cookie with Secure, measuring SPRING_SESSION writes per request, and Redis once load grows.
  • No entities in the session; a test that deserializes the previous version’s session before changing the principal class.

Remember

  • Can you say what the cookie holds, what the server keeps, and why a restart logs users out without Spring Session?
  • Can you tell idle from absolute timeout, and invalidSessionUrl from expiredUrl?
  • Can you explain maxSessionsPreventsLogin true/false and why a shared registry is needed with several instances?
  • Do you know why every session attribute must be serializable and why entities don’t belong there?
  • Can you compare the three remember-me styles by revocability and theft detection?

Interview questions

Junior

Why does a server restart log users out, and how do you fix it?

Because by default the session lives in Tomcat’s RAM; move it to an external store (Spring Session with JDBC or Redis) and restarts no longer lose it.

The external store also lets you run several instances behind a load balancer without sticky sessions.

Mid

How does maximumSessions(1) behave when the user logs in on a second device?

By default the old session is marked expired and kicked out on its next request; with maxSessionsPreventsLogin(true) the new login is rejected instead.

It relies on a SessionRegistry. One instance can use the in-memory registry (with HttpSessionEventPublisher); several instances need SpringSessionBackedSessionRegistry. Choosing true locks out anyone who forgot to log out elsewhere until the timeout.

You store an object in the session; it works locally but fails in an environment with Spring Session JDBC. Why?

An external store must serialize attributes to bytes; an object that isn’t Serializable (or holds a field that isn’t) makes the session write fail.

The real fix is to keep only small data such as ids or serializable DTOs in the session and read the rest from the database. Making the entity Serializable only treats the symptom: you still get lazy proxies, stale data, and InvalidClassException when the class changes between deploys.

What’s the difference between idle and absolute timeouts, and which does Spring support?

Idle expires after a period of inactivity (built in via spring.session.timeout); absolute expires a fixed time after creation even when active (not built in, you write it).

With only an idle timeout, a stolen session that is used continuously lives forever. An absolute timeout is a filter comparing the session’s creation time with a limit and invalidating it.

Senior

Compare Spring’s three remember-me styles. Which do you pick?

Hashed cookie: simple but can’t revoke one device. Persistent token: revocable per device and detects stolen cookies. Spring Session: extends the session itself, revocable, but loses the “remembered” versus “just typed the password” distinction.

If the app already uses Spring Session, the third is the neatest, plus your own “last re-authenticated” marker for sensitive actions. Without a shared session store and with higher security needs, use persistent tokens. The hashed cookie only suits small apps.

A user changes their password. What must a session-based system do?

Invalidate the user’s other sessions (except the current one) and all remember-me tokens, so whoever hijacked a session loses access immediately.

With Spring Session use FindByIndexNameSessionRepository.findByPrincipalName then deleteById; with persistent tokens delete the rows in persistent_logins; hashed cookies die on their own because the signature depends on the password hash. Log the event and notify the user by email.

JDBC or Redis for Spring Session?

JDBC for moderate load and fewer moving parts; Redis for high request rates or a busy main database, because each request may write LAST_ACCESS_TIME.

JDBC: easy to query and backed up with the database, but adds write load and needs a cleanup job. Redis: under 1 ms and TTL-based expiry, but one more component to keep alive (if Redis dies, everyone is logged out). Either way, measure writes per request before deciding.

Useful phrases for interviews

  • “The cookie only carries the session id; the data stays on the server.”
  • “Spring changes the session id on login to prevent session fixation.”
  • “We use a thirty-minute idle timeout plus a twelve-hour absolute timeout.”
  • “With one allowed session, the oldest one is expired on its next request.”
  • “In a cluster the session registry must read from the shared store.”
  • “Everything in the session has to be serializable once it leaves the JVM.”
  • “A shared session store removes the need for sticky sessions.”
  • “Persistent remember-me tokens rotate on every use, so a mismatch signals cookie theft.”
  • “Server-side sessions can be revoked instantly, which is why we log out everywhere on a password change.”
  • “The session store, not the cookie’s Max-Age, is the source of truth for expiry.”

Notes based on Hỏi Dân IT course material, rewritten and extended in my own words.