skip to content

What is the 'remember-me' feature in Spring Security, and how do you enable it?

level: juniorimportance: should knowfreq 45%

answer

  1. cookie outlives the session
  2. http.rememberMe(...)
  3. default validity = 2 weeks
  4. set a stable key or restarts invalidate
  5. 'remembered' != 'fully authenticated'

basics

~10 s

Remember-me keeps a user logged in across browser restarts by sending a long-lived cookie instead of relying only on the session. You enable it with the rememberMe() method in the SecurityFilterChain configuration.

solid answer

~40 s

Remember-me lets a returning user stay authenticated after their HTTP session expires (e.g. closing the browser). On login, Spring Security issues a persistent cookie (default 'remember-me'); on a later request with no session, that cookie re-authenticates the user. Enable it in the HttpSecurity DSL via http.rememberMe(...). Normally the user opts in through a checkbox whose request parameter is 'remember-me'. You should always set a stable key so tokens survive application restarts. The two built-in strategies are TokenBasedRememberMeServices (a signed hash cookie, no database) and PersistentTokenBasedRememberMeServices (a series/token row in a table). Remember-me authentications are marked as 'remembered' rather than 'fully authenticated', so you can still force a fresh login for sensitive actions.

code

java · 11 lines
java
@Bean
SecurityFilterChain security(HttpSecurity http) throws Exception {
    http
        .formLogin(Customizer.withDefaults())
        .rememberMe(rm -> rm
            .key("change-me-in-prod")          // stable secret; survives restarts
            .tokenValiditySeconds(1209600)      // 14 days (default)
            .rememberMeParameter("remember-me") // login form checkbox name
            .rememberMeCookieName("remember-me"));
    return http.build();
}

go deeper

for a junior

Know it keeps users logged in via a cookie and is enabled with rememberMe().

for a middle

Explain the cookie flow, the checkbox parameter, and the importance of a stable key.

for a senior

Contrast the two strategies and the remembered-vs-fully-authenticated distinction.

for a principal

Reason about cluster/key management and gating sensitive operations behind fullyAuthenticated.

**The problem it solves.** Normal authentication in a web app is tied to the HTTP session: after you log in, the server stores your `Authentication` in the `SecurityContext`, keyed by the session cookie (`JSESSIONID`). When the session expires or the browser is closed, that link is gone and you must log in again. **Remember-me** (a.k.a. 'remember-my-login') addresses this by issuing a *separate, longer-lived cookie* so the user can be silently re-authenticated on a future visit without re-entering credentials. **How it flows.** 1. On a successful form login, if the user opted in (typically a checkbox named `remember-me`), Spring Security's `RememberMeServices` writes a remember-me cookie to the browser (default cookie name `remember-me`, default validity **two weeks** / 1,209,600 seconds). 2. On a later request where there is **no** authenticated session, the `RememberMeAuthenticationFilter` sees an unauthenticated context, reads the cookie, validates it, and if valid populates the `SecurityContext` with a `RememberMeAuthenticationToken`. **Enabling it.** In the modern lambda DSL: ```java http.rememberMe(rm -> rm.key("a-stable-secret").tokenValiditySeconds(1209600)); ``` Calling `rememberMe()` wires up (a) a `RememberMeServices` implementation, (b) the `RememberMeAuthenticationFilter`, and (c) a `RememberMeAuthenticationProvider` in the `AuthenticationManager`. **The two strategies.** - `TokenBasedRememberMeServices`: the cookie itself is a self-contained signed hash (username + expiry + password-hash + key). No storage needed. - `PersistentTokenBasedRememberMeServices`: a `series`/`token` pair is stored in a database table (`persistent_logins`), enabling token rotation and stolen-cookie detection. **The `key`.** This is a secret string mixed into the token signature. If you don't set one, Spring generates a *random* key at startup — which means every restart invalidates all existing remember-me cookies. Always set a fixed `key` in production. **'Remembered' vs 'fully authenticated'.** A remember-me login yields a `RememberMeAuthenticationToken`. Spring treats this as a weaker trust level: `isFullyAuthenticated()` (the `fullyAuthenticated` authorization expression) returns **false** for it, while `isAuthenticated()` returns true. This lets you allow remember-me users to browse but demand a fresh password entry (`fullyAuthenticated`) before changing a password or making a payment. **Gotchas.** The checkbox parameter name must match what `RememberMeServices` expects (`remember-me` by default; configurable via `rememberMeParameter`). Remember-me does not extend server sessions — it recreates authentication from the cookie. Logging out clears the remember-me cookie. **When to use.** Consumer-facing apps where convenience matters. Avoid or restrict it in high-security contexts, or gate sensitive operations behind `fullyAuthenticated`.

  • Why should you explicitly set the key?
    The key signs the token. If omitted, Spring generates a random key at startup, so every application restart (or each instance in a cluster) invalidates all remember-me cookies, silently logging users out.
  • Does remember-me extend the HTTP session?
    No. It doesn't keep a session alive; it recreates an Authentication from the cookie on a new request when no session exists.

saying these in an interview costs you the question

  • Thinking remember-me just extends the session timeout
  • Believing a remember-me user is fully authenticated for all purposes
  • Not knowing a missing key causes logouts on restart

context