Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 39 ยท Authentication Mechanisms

Remember-Me, Session Management and Fixation

Understand remember-me cookies (hash-based and persistent token), session fixation protection, concurrent session limits and timeouts, and how to choose safe defaults.

A session cookie lasts until the browser closes or the server forgets the session. Users, though, expect "keep me signed in" on their own laptop. At the same time, the longer a login lives, the more it is worth stealing. This lesson covers the tools Spring Security offers for that balance: remember-me cookies, session fixation protection, concurrent session control and timeouts.

The real configuration is read-only here, because a servlet container is not available; the examples that run model the cookies and the session table so you can see each rule in action.

Remember-me: a second, longer-lived login

Remember-me adds a cookie (remember-me by default) that can re-create the login when the session is gone. It is only consulted if the request is not otherwise authenticated.

Java
http.rememberMe(r -> r
    .key(rememberMeKey)                    // secret used to sign the cookie
    .tokenValiditySeconds(14 * 24 * 3600)  // 14 days
    .rememberMeParameter("remember")       // checkbox name in the form
    .userDetailsService(userDetailsService));

Two implementations exist:

Kind Cookie content Server state Revocation
Hash-based (TokenBasedRememberMeServices) username:expiry:hash(username, expiry, password, key) None Changing the user's password invalidates the cookie
Persistent token (PersistentTokenBasedRememberMeServices) series:token A table of series and tokens Delete the row

The hash-based variant is simple but weak: the cookie is a bearer credential that stays valid until it expires, even if stolen, and it cannot be revoked short of changing the password. The persistent variant rotates the token at every use and detects theft: if a stolen series arrives with an old token, the server knows two parties hold the cookie, deletes the series and throws a CookieTheftException. Prefer persistent tokens in anything serious.

A remember-me login produces a weaker Authentication (a RememberMeAuthenticationToken). Treat it as less trustworthy than a fresh password login: authenticated() rules accept it, but sensitive actions (change password, payment) should demand fullyAuthenticated(), which requires a real login in this session.

Java
.authorizeHttpRequests(a -> a
    .requestMatchers("/account/security/**").fullyAuthenticated()
    .anyRequest().authenticated())

Persistent tokens, step by step

Java Persistent remember-me with token rotation and theft detection (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The theft detection has a price: the legitimate user is logged out too, and sees a message. That is the right outcome; it also tells you to rotate the password.

Session fixation

In a session fixation attack, the attacker obtains a valid session id from the site (for example by simply visiting it), plants it in the victim's browser (through a crafted link or a subdomain cookie), waits for the victim to log in, and then uses the same id to act as the victim. The defense is to issue a new session id when the privilege level changes. Spring Security does that by default after authentication:

Java
http.sessionManagement(s -> s
    .sessionFixation(f -> f.changeSessionId()));      // default on Servlet 3.1+

The alternatives are newSession() (a new session and discard attributes), migrateSession() (copy attributes to a new session) and none() (do not use). Keep the default. A frequent bug is custom login code that authenticates but never rotates the id, so check hand-written login endpoints for it.

Java Session fixation with and without id rotation (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Concurrent sessions and timeouts

Java
http.sessionManagement(s -> s
    .maximumSessions(1)
    .maxSessionsPreventsLogin(false)               // false = the new login expires the old session
    .expiredUrl("/login?expired"));

maximumSessions(1) needs a SessionRegistry with the right HttpSessionEventPublisher bean so session destruction is noticed; with maxSessionsPreventsLogin(true) the second login is refused instead, which locks users out if a session was left open elsewhere.

Timeouts are a container setting, not a Spring Security one:

PROPERTIES
server.servlet.session.timeout=30m
server.servlet.session.cookie.secure=true
server.servlet.session.cookie.http-only=true
server.servlet.session.cookie.same-site=lax

The three cookie flags are part of the defense: Secure keeps the cookie off plain HTTP, HttpOnly hides it from JavaScript (so an XSS bug cannot read it) and SameSite limits cross-site sending. More on them in security headers and sessions.

A small model of the "newest wins" policy (maxSessionsPreventsLogin(false)):

Java maximumSessions(1): the newest login wins (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Choosing defaults

  • Banking or admin tools: no remember-me, short idle timeout, one session per user.
  • Normal consumer site: persistent remember-me for 14 to 30 days, fullyAuthenticated() for account changes, default fixation protection.
  • API with tokens: none of this applies; see JWT and resource servers.

Never use remember-me together with STATELESS configuration expecting it to work: it needs a login request to create the cookie and the framework to read it, so reserve it for the browser-facing chain (see multiple filter chains).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main advantage of persistent-token remember-me over the hash-based version?

    A stale token reveals that two parties hold the cookie, so the series is deleted.
  2. 2. What does session fixation protection do after a successful login?

    Rotating the id at login removes the attacker's pre-known value.
  3. 3. Which rule should protect a change-password page when remember-me is enabled?

    fullyAuthenticated() rejects remember-me logins, forcing a fresh password entry for sensitive actions.
  4. 4. What does maxSessionsPreventsLogin(false) do with maximumSessions(1)?

    The newest login wins and the oldest session is marked expired.

Summary

  • Remember-me re-creates a login from a long-lived cookie; choose persistent tokens, which rotate and detect theft.
  • Sensitive operations should require fullyAuthenticated().
  • Session fixation protection issues a new session id on login; keep the default and check custom login code.
  • maximumSessions limits concurrent logins; timeouts and cookie flags (Secure, HttpOnly, SameSite) are container settings.
  • Match these features to the sensitivity of the application.

Next: Roles and authorities