Skip to content

    System Design

    Authentication Flows End to End

    Server side of sign-in: password hashing, a cookie session, token login with refresh rotation, logout, and defences against brute force and account enumeration.

    By Published 17 min read

    Share

    Flagship lessonadvancedSpring Boot labBackend System Design

    Before this: OAuth 2.0, OpenID Connect and PKCE, JWT: Structure and Pitfalls

    What you'll learn: By the end of this lesson you will be able to store and check passwords with a slow salted hash, run a cookie-session login that rotates the session id and survives CSRF checks, run a token login with short-lived access tokens and rotating refresh tokens that detect theft, end a login properly on the server, answer failed logins so they reveal nothing, and throttle brute-force attempts without handing attackers a lockout weapon, using a Spring Boot lab you can run.

    A members' club has a door. At the door you show your ID and staff check the list; if you pass, you get a wristband. Inside, bouncers look at the wristband, not at your face. When you leave, staff cut the band off, because a band in someone else's pocket is still a band. Staff never tell a stranger whether a name is on the list, and if one person guesses names all night, the door closes to that person. That is the server side of sign-in.

    The browser half of this story is already published: Authentication Flows From the SPA to the API shows what the page does, Token Storage and Secure Cookies shows where the credential should live, and Authentication vs Authorization in the UI shows why the interface is never the control. This lesson is what the server does at each of those steps. The concepts are in Authentication vs Authorization, Sessions vs Tokens, the machinery in Spring Security Architecture and the Filter Chain. OAuth 2 and OpenID Connect, JWT internals and role models are separate lessons.

    The core idea

    Every sign-in flow does four things on the server, in this order: verify a secret slowly and uniformly, mint a credential that means nothing by itself, check that credential on every request, and end it on the server. Around those four sits a front door that must not leak and must not be hammered.

    Three illustrations run through the lesson:

    • Minimal example: the Spring Boot lab, which runs a cookie-session login and a token login against a real embedded server.
    • Realistic example: ShopStream's web dashboard and mobile app, in "In practice".
    • Failure example: a stolen or replayed refresh token, and a lockout rule that can be turned against the user it protects.

    The shape of the server

    Figure 1. The server-side pieces of one login.

    A login request passes a throttle, a password check against a user store and an audit log, then mints a session or tokensClient to Login endpoint (credentials); Login endpoint to Throttle (check first); Login endpoint to User store (verify hash); Login endpoint to Audit log (record); Login endpoint to Session store (mint); Login endpoint to Token store (mint)IDENTITY SERVICEClient: web or mobileClientweb or mobileLogin endpoint: one shared serviceLogin endpointone sharedserviceThrottle: per accountThrottleper accountUser store: password hashesUser storepassword hashesAudit log: reasons kept hereAudit logreasons kept hereSession store: cookie flowSession storecookie flowToken store: token flowToken storetoken flowcredentialscheck firstverify hashrecordmintmint

    How to read this: both flows share one login service. It consults the throttle before touching a password, checks the hash against the user store, records every outcome with its true reason in the audit log, and only then mints a session or a pair of tokens.

    Step one: storing and checking passwords

    Plan for the day the password table leaks: what you store must make guessing expensive. The Spring Security reference says validation with an adaptive one-way function is "intentionally resource-intensive", with a "work factor" that grows as hardware improves, and recommends tuning it so verification takes about one second on your system. It also warns that, because of that cost, validating a username and password on every request "can significantly degrade the performance" of an application. That is the real reason sessions and tokens exist: the expensive check happens once, at login.

    Three details of the stored string matter:

    • A unique salt per password. The OWASP Password Storage Cheat Sheet requires one, so precomputed lookup tables are useless. Libraries generate it for you.
    • An algorithm and a cost you can raise. OWASP's first choice is Argon2id (minimum 19 MiB of memory, 2 iterations, parallelism 1); bcrypt is listed for legacy systems, with a work factor of at least 10 and a 72-byte limit on the password. Spring's DelegatingPasswordEncoder prefixes the hash with the algorithm id, such as {bcrypt}, so hashes made with different settings can live side by side. Spring's Argon2PasswordEncoder requires BouncyCastle on the classpath.
    • A way to upgrade. OWASP's advice is to re-hash at the user's next successful login, the one moment you hold the plaintext. Spring supports it: PasswordEncoder.upgradeEncoding says whether a stored hash should be encoded again, and a UserDetailsPasswordService stores the new one.

    The lab uses bcrypt through DelegatingPasswordEncoder because it needs no extra library: a teaching choice, not a recommendation over Argon2id. The work must also be the same whether or not the account exists: returning early for unknown usernames would let response time reveal which accounts exist, as OWASP's Authentication Cheat Sheet warns. The lab counts hash comparisons for both cases.

    For a browser app with its own backend, the session cookie is the default (see the basics lesson). The server's duties at login are specific:

    Figure 2. A cookie-session login, as the server sees it.

    sequenceDiagram accTitle: Cookie session login on the server accDescr: The page first obtains a CSRF token cookie. It posts credentials with the token in a header. The server throttles, verifies the password, rotates the session id, saves the security context in the session and returns a session cookie. Later requests carry the cookie. Logout invalidates the session on the server. participant P as Page participant S as Server participant H as Session store P->>S: GET /web/csrf S-->>P: Set-Cookie XSRF-TOKEN P->>S: POST /web/login + X-XSRF-TOKEN header S->>S: throttle check, verify password hash S->>H: new session id, save security context S-->>P: 200 + Set-Cookie session id P->>S: GET /web/me (cookie) S-->>P: 200 user P->>S: POST /web/logout + X-XSRF-TOKEN header S->>H: invalidate session S-->>P: 204 + cookie expired

    How to read this: the CSRF token travels in a header the page copies from a cookie, the session id travels in a cookie the page cannot read. Logout is a server action on the store, not just a cookie being deleted.

    Here is the login handler from the lab:

        @PostMapping("/web/login")
        Map<String, String> login(@RequestBody LoginRequest body, HttpServletRequest request, HttpServletResponse response) {
            Authentication authentication = logins.login(body.username(), body.password());
            // A new session id for the new privilege level; attributes of the old session (here: "next") are kept.
            fixationProtection.onAuthentication(authentication, request, response);
            SecurityContext context = holder.createEmptyContext();
            context.setAuthentication(authentication);
            holder.setContext(context);
            contextRepository.saveContext(context, request, response); // since Spring Security 6 this must be explicit

    Each line is a rule:

    • Rotate the session id at login. OWASP: the id "must be renewed or regenerated by the web application after any privilege level change". Without it, an id an attacker planted before login would carry the authenticated session (session fixation). Spring's changeSessionId strategy is the default for the built-in form login; a hand-written login endpoint must call a SessionAuthenticationStrategy itself, because the reference says authentication mechanisms must invoke it.
    • Save the context explicitly. Since Spring Security 6, "users now must explicitly save the SecurityContext with the SecurityContextRepository" if it should persist between requests. A custom login that skips saveContext authenticates once and then forgets the user.
    • Keep the id opaque. OWASP asks for at least 64 bits of entropy from a secure generator and a generic cookie name; the lab renames the cookie.
    • Set the cookie's attributes. The lab's properties make the server send Secure, HttpOnly, SameSite=Lax, Path=/ and no Domain, and name the cookie __Host-sid. MDN's rule for the __Host- prefix is that a cookie must be set with Secure over HTTPS, with no Domain and Path=/, so a sibling subdomain cannot overwrite it.
    • Require a CSRF token, including on login. The Spring reference says it is important to require CSRF for login requests "to protect against forging log in attempts", and the lab turns on csrf.spa(): an XSRF-TOKEN cookie the page can read and a header it sends back. Only a backend that does not serve browser traffic may disable CSRF.

    The web chain that wires this, including Spring's own logout filter:

        @Bean
        @Order(2)
        SecurityFilterChain webChain(HttpSecurity http) {
            http
                .securityMatcher("/web/**")
                .csrf(csrf -> csrf.spa()) // XSRF-TOKEN cookie readable by the page, sent back in X-XSRF-TOKEN
                .exceptionHandling(e -> e.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)))
                .logout(l -> l
                    .logoutUrl("/web/logout")
                    .deleteCookies("__Host-sid")
                    .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.NO_CONTENT)))
                .authorizeHttpRequests(a -> a
                    .requestMatchers("/web/csrf", "/web/start", "/web/login", "/web/password-reset").permitAll()
                    .anyRequest().authenticated());
            return http.build();
        }

    The /web/start endpoint keeps the path the user was heading for in the pre-login session and accepts only local paths, so a link cannot turn the login into an open redirect. The attribute survives the id rotation, which the lab checks.

    Step two and three: tokens

    A mobile app has no cookie jar the browser manages, so it holds tokens and sends them in a header. RFC 6750 defines the Authorization: Bearer scheme, says the resource server must answer a request without usable credentials with a WWW-Authenticate header, and says token servers should issue short-lived bearer tokens, one hour or less. The lab issues two opaque tokens per login:

    • an access token valid for 15 minutes (illustrative), presented on every call;
    • a refresh token valid for 7 days (illustrative), presented only to get a new pair.

    Both are 256 bits from the platform's secure random generator and carry no data. The server stores only their SHA-256 hashes, so a leaked copy of the token store holds nothing a client can present. Signed, self-describing tokens such as JWTs are the subject of the JWT lesson in this module, and OAuth 2 and OpenID Connect is the standard way to hand tokens to apps.

    This lab's /token/login is a deliberate first-party simplification to show the server mechanics. It is not an OAuth grant, and it should not be copied as one: RFC 9700, the OAuth security best current practice, says the resource owner password credentials grant "MUST NOT be used", and recommends the authorization code flow with PKCE.

    Figure 3. What happens to a refresh token.

    stateDiagram-v2 accTitle: Lifecycle of a rotating refresh token accDescr: A refresh token is issued at login. Presenting it once exchanges it for a new pair and marks it used. Presenting a used token again is treated as theft and revokes the whole login. Logout also revokes the whole login. An expired token is simply refused. [*] --> Active: login issues the pair Active --> Used: presented once, new pair issued Used --> Revoked: presented again, whole login revoked Active --> Revoked: logout Active --> Expired: lifetime ends Revoked --> [*] Expired --> [*]

    How to read this: a refresh token is good for exactly one exchange. A second use is evidence that two parties hold it, so the server ends the whole login, which forces the real user to sign in again.

    Rotation is the defence RFC 9700 asks for when refresh tokens are not bound to a client key: "Refresh tokens for public clients MUST be sender-constrained or use refresh token rotation". With rotation the authorization server issues a new refresh token with every refresh response and invalidates the previous one while remembering the relationship; if the old one is presented again, it "cannot determine which party submitted the invalid refresh token" but "it will revoke the active refresh token", which "stops the attack at the cost of forcing the legitimate client to obtain a fresh authorization grant". The lab's refresh does exactly that, and also removes the family's access tokens:

        synchronized Optional<Issued> refresh(String refreshToken) {
            String hash = sha256(refreshToken);
            RefreshRecord rec = refreshTokens.get(hash);
            if (rec == null) {
                return Optional.empty();
            }
            if (rec.used()) {
                revokeFamily(rec.family()); // reuse of a rotated token: assume theft, end the whole login
                return Optional.empty();
            }
            if (!clock.instant().isBefore(rec.expiresAt())) {
                return Optional.empty();
            }
            refreshTokens.put(hash, new RefreshRecord(rec.user(), rec.family(), rec.expiresAt(), true));
            return Optional.of(issueInFamily(rec.user(), rec.family()));
        }

    One implementation note from the lab: the entry point for the token chain sets the 401 status instead of calling sendError. Spring Security authorizes every dispatch, including the container's error dispatch (the reference says the AuthorizationFilter "runs not just on every request, but on every dispatch"), so a sendError(401) on a path no chain permits turns into a 403.

    Ending it: logout and revocation

    Logout must end the credential on the server. OWASP: the application "must invalidate the session at least on server side"; deleting the browser cookie does not stop a copy someone else holds. Spring's default logout invalidates the HTTP session, clears the SecurityContextHolder and the SecurityContextRepository, and clears the saved CSRF token. The lab uses that filter, adds a cookie-expiry header and returns 204. For tokens, logout revokes the whole family, so the access token dies with the refresh token, because the lab looks tokens up in the server's store. A self-contained signed token cannot be recalled that way, the central trade-off of the JWT lesson.

    The lab runs over plain HTTP on the loopback interface, so the cookie-deletion header it prints carries no Secure attribute. Whether a browser accepts a deletion header without Secure for a __Host- cookie is a browser question the lab cannot answer, so check the real behaviour behind your TLS terminator. What the lab does test is the part that matters: replaying the old session id afterwards gets a 401.

    The front door: say the same thing every time

    OWASP's Authentication Cheat Sheet is direct: respond "with a generic error message regardless of whether" the user id was wrong, the password was wrong or the account is locked, and note that even if the page looks identical, "the HTTP response code may differ which can leak information". Its example login message is "Login failed; Invalid user ID or password". The same goes for password reset ("If that email address is in our database, we will send you an email to reset your password") and for registration. The Forgot Password Cheat Sheet adds: consistent responses for existing and missing accounts, consistent timing, no automatic login after a reset, and rate limits per account.

    Spring helps: by default the base class of DaoAuthenticationProvider throws a BadCredentialsException both for an unknown username and a wrong password; its API documentation calls the alternative "less secure". The lab keeps the reason where only operators can see it:

        Authentication login(String username, String password) {
            String key = username == null ? "" : username.strip().toLowerCase(Locale.ROOT);
            if (throttle.isLocked(key)) {
                audit.record("LOGIN_BLOCKED " + key);
                throw new TooManyAttemptsException();
            }
            try {
                Authentication result = authenticationManager.authenticate(
                    UsernamePasswordAuthenticationToken.unauthenticated(key, password));
                throttle.reset(key);
                audit.record("LOGIN_SUCCESS " + key);
                return result;
            } catch (AuthenticationException e) {
                throttle.recordFailure(key);
                // Internal detail for the log only. The response is the same for both reasons.
                String reason = userStore.userExists(key) ? "wrong-password" : "unknown-user";
                audit.record("LOGIN_FAILURE " + key + " reason=" + reason);
                throw new InvalidCredentialsException();
            }
        }

    OWASP also says to log and review authentication failures and lockouts: that is how an attack becomes visible. See Audit Logging.

    Brute force, credential stuffing and the lockout trap

    Three attacks hit a login form: brute force (many passwords against one account), credential stuffing (breached pairs against many accounts) and password spraying (one weak password against many accounts). OWASP calls multi-factor authentication "by far the best defense against the majority of password-related attacks". Short of that, the lab applies the throttling advice:

    • Count failures per account, not per address. OWASP: the counter "should be associated with the account itself, rather than the source IP address". Its credential-stuffing sheet explains why per-address limits alone are weak: attack tools distribute requests across many addresses.
    • Count the name that was typed, even if no such account exists. Otherwise the lock itself reveals which names are real. In the lab, mallory (no account) locks exactly like carol.
    • Lock out the right password too. During a lock the correct password is refused, so a guesser cannot confirm a guess.
    • Beware of denial of service. OWASP warns that care must be taken to prevent lockouts "from being used to cause a denial of service by locking out other users' accounts", and suggests letting the password-recovery flow work while an account is locked, and exponential lockouts that start very short and double. The lab's flat 15-minute lock (illustrative) is the simplest version and has this weakness.
    • CAPTCHA only as defence in depth, and breached-password checks for new passwords. Rate Limiting covers limits at the edge.

    Figure 4. One login attempt through the throttle.

    flowchart TD accTitle: Decision path of a login attempt accDescr: The server first checks whether the submitted account name is locked and answers 429 if so. Otherwise it verifies the password. Success resets the counter and mints a credential. Failure records the failure, writes the real reason to the audit log and answers 401 with the same generic body whatever the reason. A["Login attempt
    (name typed by the client)"] --> L{"Name locked?"} L -->|"yes"| B["Audit: blocked
    429, generic body"] L -->|"no"| V{"Password hash matches?
    (same work if the account is unknown)"} V -->|"yes"| S["Reset counter, audit: success
    mint session or tokens"] V -->|"no"| F["Count failure, audit: real reason
    401, same generic body"]

    How to read this: the check order matters. The lock is tested before the password so a locked name never reaches the hash, and every failure leaves the front door with the same face.

    Build it: both flows against a real server

    This is the minimal example and the failure cases. Goal: run the cookie-session flow and the token flow end to end and read what the server really sent. Not a real deployment: the server is Spring Boot's embedded Tomcat on a random loopback port, called with Java's HttpClient and a hand-made cookie jar; users and tokens live in memory (Spring's InMemoryUserDetailsManager and an in-memory token store); the clock is a test clock the scenarios move forward. No Docker is used.

    Setup. From the repository:

    cd examples/spring-labs
    ./gradlew :labs:auth-flows-end-to-end:test

    It runs 12 tests, one of which compares the report below with examples/spring-labs/golden/auth-flows-end-to-end.txt. The code is in examples/spring-labs/labs/auth-flows-end-to-end/. Random values (session ids, tokens, hash bodies) are masked in the report.

    Scenario 1: the stored hash. Same password, two hashes, both verify.

    Expected output, captured from a real run (Spring Boot 4.1.2, Spring Security 7.1.2, Java 25 language level, 2026-12-01):

    stored form starts with: {bcrypt}$2a$10$  (length 68)
    same password hashed twice gives the same string: false
    both hashes verify the right password: true
    a wrong password verifies: false

    The 10 is the bcrypt cost, Spring's default strength. The strings differ because each carries its own random salt.

    Scenario 2: the cookie session. Return-path guard, CSRF cookie, login refused without the header and accepted with it, the server's real Set-Cookie, id rotation, and logout that kills the session on the server.

    Expected output, captured from a real run (the same run):

    GET /web/start?next=//evil.example/x -> 200 {"next":"/"}   (not a local path, so it is replaced)
    GET /web/start?next=/orders -> 200 {"next":"/orders"}
    session cookie before login: true
    GET /web/csrf -> 200
    POST /web/login without the CSRF header -> 403
    POST /web/login with the CSRF header -> 200 {"user":"alice","next":"/orders"}
      Set-Cookie: __Host-sid=<value>; Path=/; Secure; HttpOnly; SameSite=Lax
    session id changed at login: true
    old session id still accepted: false
    GET /web/me with the new cookie -> 200 {"user":"alice","via":"session"}
    POST /web/logout without the CSRF header -> 403
    POST /web/logout with the CSRF header -> 204
      Set-Cookie: __Host-sid=; Expires=Thu, 01 Jan 1970 00:00:10 GMT; Path=/; SameSite=Lax
      Set-Cookie: XSRF-TOKEN=; Expires=Thu, 01 Jan 1970 00:00:10 GMT; Path=/
    replaying the session cookie from before logout: GET /web/me -> 401

    Scenario 3: tokens. After the second use of refresh token 1, even refresh token 2 and access token 2 are dead: the whole login was revoked. The old access token kept working after rotation until it expired, which is why access tokens are short-lived.

    Expected output, captured from a real run (the same run):

    POST /token/login -> 200 {"accessToken":"<token>","refreshToken":"<token>","expiresInSeconds":900}
    GET /token/me with no token -> 401 (WWW-Authenticate: Bearer)
    GET /token/me with the access token -> 200 {"user":"alice","via":"token"}
    POST /token/refresh with refresh token 1 -> 200 {"accessToken":"<token>","refreshToken":"<token>","expiresInSeconds":900}
    new tokens differ from the old ones: true
    old access token still works (until it expires): 200
    POST /token/refresh with refresh token 1 AGAIN (reuse) -> 401 {"error":"invalid_token"}
    POST /token/refresh with refresh token 2 afterwards -> 401 (the whole login was revoked)
    GET /token/me with access token 2 afterwards -> 401
    16 minutes later, access token -> 401
    16 minutes later, refresh token -> 200
    8 days later, refresh token -> 401
    POST /token/logout -> 204
    after logout: refresh -> 401, access -> 401

    Scenario 4: the same face for every failure. A wrong password and an unknown account get the same status and body, with one hash comparison each (the lab counted comparisons; it did not measure response times). The audit log keeps the real reasons, and only the server-side outbox shows that one reset email was queued.

    Expected output, captured from a real run (the same run):

    known account, wrong password   -> 401 {"error":"invalid_credentials"}
    unknown account                 -> 401 {"error":"invalid_credentials"}
    responses identical: true
    password hash comparisons done: known 1, unknown 1
    what the audit log recorded (never sent to the client):
      LOGIN_FAILURE carol reason=wrong-password
      LOGIN_FAILURE nobody reason=unknown-user
    password reset, known account   -> 202 {"message":"If that account exists, we will send an email."}
    password reset, unknown account -> 202 {"message":"If that account exists, we will send an email."}
    responses identical: true
    emails queued (visible only to the server): [reset link queued for carol]

    Scenario 5: the throttle. Five wrong guesses lock both the real and the invented name; the right password is refused during the lock; another account is unaffected; the lock ends after the window.

    Expected output, captured from a real run (the same run):

    5 wrong guesses, status codes: carol (real account) [401, 401, 401, 401, 401], mallory (no such account) [401, 401, 401, 401, 401]
    next attempt for carol with the RIGHT password -> 429 {"error":"too_many_attempts"}
    next attempt for mallory                        -> 429 {"error":"too_many_attempts"}
    another account (sam) is not affected           -> 200
    16 minutes later, carol with the right password  -> 200
    audit log lines for carol:
      LOGIN_FAILURE carol reason=wrong-password
      LOGIN_FAILURE carol reason=wrong-password
      LOGIN_FAILURE carol reason=wrong-password
      LOGIN_FAILURE carol reason=wrong-password
      LOGIN_FAILURE carol reason=wrong-password
      LOGIN_BLOCKED carol
      LOGIN_SUCCESS carol

    Scenario 6: re-hashing at login. A user whose stored hash used a weaker cost is upgraded the next time the right password arrives.

    Expected output, captured from a real run (the same run):

    stored hash of 'legacy' before login starts with: {bcrypt}$2a$04$
    POST /web/login -> 200
    stored hash of 'legacy' after login starts with:  {bcrypt}$2a$10$

    Break it. In LoginService.login, move the throttle.isLocked check below the authenticationManager.authenticate call: the lock test must fail, because the right password then succeeds during a lock. Restore the order and re-run.

    Left out: multi-factor authentication, passkeys, remember-me, reset tokens, registration, TLS (plain HTTP on loopback) and any real database.

    Trade-offs

    Choice Gain Cost Wrong when
    Cookie session Nothing for script to read; instant revocation; browser handles it Session store; CSRF defence The client is not a browser
    Opaque token with rotation Instant revocation; theft detection A store lookup per request; client must refresh carefully Thousands of services must verify without a shared store
    Per-account lockout Stops guessing at one account Attacker can lock a victim out Used as the only defence
    Generic failure messages No account enumeration Harder support conversations Never, for the public response

    In practice: ShopStream sign-in for web and mobile

    This is the realistic example on ShopStream, the course's running system. It is an educational scenario and every number is an illustrative assumption.

    This is a realistic scenario, not a case history.

    The situation

    ShopStream has a store dashboard in the browser and a shopper app on phones. About 2,300 browsing requests per second arrive at peak (illustrative). The team owns one Identity service and wants one login service behind both clients.

    Starting architecture

    Figure 5. Two clients, two credentials, one login service.

    The dashboard uses a session cookie and the mobile app uses rotating tokens, both issued by one Identity serviceStore dashboard to Identity service (cookie login); Shopper app to Identity service (token login); Identity service to Session store (session); Identity service to Token store (tokens); Identity service to Audit log (events); Orders API to Session store (lookup); Orders API to Token store (lookup)Store dashboard: browserStoredashboardbrowserShopper app: mobileShopper appmobileIdentity service: login, throttleIdentityservicelogin, throttleSession storeSession storeToken storeToken storeOrders API: checks credentialOrders APIchecks credentialAudit logAudit logcookie logintoken loginsessiontokenseventslookuplookup

    How to read this: the Identity service mints; the Orders API only looks credentials up. Both stores can end a login instantly.

    Options considered

    Option Gain Cost Wrong when
    A. Opaque tokens everywhere, stored by the browser app in script-readable storage One mechanism One script flaw exposes every token A browser holds high-value access
    B. Cookie session for the dashboard, rotating opaque tokens for the app Right tool per client; instant revocation Two flows and two stores The team cannot operate two stores
    C. Delegate sign-in to an identity provider with OAuth 2 and OpenID Connect Standard flows, less to own Redirects, provider dependency A very small team with one client

    The decision

    Option B for now, with the login service shared, so throttling, hashing, audit and generic errors exist once. Moving to an identity provider is a later step (the OAuth 2 and OpenID Connect lesson covers it). Session idle and absolute timeouts come from OWASP's examples (illustrative: 30 minutes idle, 8 hours absolute); the refresh lifetime is 7 days (illustrative).

    Rollout and verification

    Ship the login service behind the dashboard first, with per-account throttling on and an alert on lockouts, then add the token endpoints. For each flow use the lab's scenarios as a checklist: id rotation, CSRF refusal, identical failure bodies, reuse detection, logout then replay.

    The 2 a.m. failure

    Support reports mobile users being signed out at random after the token release. The audit log shows refresh-token reuse events, each followed by a revoked login. The cause is an app that fires several requests at once; each gets a 401 for the expired access token, each refreshes, and the second refresh presents a token the first already rotated. The server cannot tell a race from theft (RFC 9700 says the same of the two parties), so it ends the login. First three checks: (1) count reuse events per device and look at the time gap between the two refreshes; (2) check whether the app has a single refresh in flight at a time (the frontend lesson calls this single flight); (3) confirm the rotation release date matches the start of the reports. Mitigation: ship a client fix that serialises refreshes; some teams also accept a short grace window for the previous token, which trades some theft detection for fewer false alarms and should be a deliberate decision. Follow-up: an alert on reuse events per hour and a test with parallel refreshes.

    Architect's notes

    • One login service for every client. Throttle, hash, audit and generic errors in one place cannot drift.
    • Keep reasons in the audit log, never in the response, and alert on lockouts and refresh reuse.
    • Pair every lockout rule with a recovery path, so it cannot shut a customer out for good.

    Common mistakes

    • Different messages or status codes for unknown account and wrong password, including on reset and registration.
    • Keeping the session id across login, or forgetting to save the security context in a hand-written login.
    • Counting failures per address only, or counting only for accounts that exist.
    • Refresh tokens that never rotate, or rotation without reuse handling.
    • Logout that only deletes the cookie or only forgets the token on the device.

    Key takeaways

    • Verify slowly and uniformly: a salted adaptive hash, the same work for unknown accounts, a cost you can raise at the next login.
    • A cookie session needs id rotation at login, an explicit security-context save, protective cookie attributes and CSRF tokens.
    • A token flow needs short-lived access tokens and rotating refresh tokens whose reuse revokes the whole login.
    • Logout ends the credential on the server; clearing the client is cleanup.
    • Every failure leaves the front door with the same status and body; the real reason goes to the audit log.
    • Throttle per account on the typed name, lock out the right password too, and keep the lockout from being weaponised.

    Practice exercises

    Exercise 1 (30 min). Run the lab and read the golden file. Which lines would change if LoginThrottle.MAX_FAILURES became 3? Change it, run the tests, check your prediction, then restore the value.

    Exercise 2 (1 hour). Add an idle timeout of 30 minutes (illustrative) to the token store: an access token unused for 30 minutes is refused. Use the test clock and write the test first.

    Exercise 3 (1 hour). Change the lockout to exponential: the lock starts at 1 second and doubles per lockout, capped at 15 minutes (illustrative). What does the golden file look like now, and what attack does it still allow?

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments