Skip to content

    Frontend System Design

    JWTs, Single Sign-On and the Session Lifecycle

    Learn how to validate a JWT, why signed-in is several clocks, how refresh rotation and single sign-on work, and what each kind of sign-out really ends.

    By Published 17 min read

    • frontend-system-design
    • jwt
    • sso
    • sessions
    • authentication
    Share

    Standard lessonintermediateTypeScript labFrontend System Design

    Before this: OAuth 2.0, OIDC and PKCE in Single-Page Apps

    What you'll learn: By the end of this lesson you will be able to read the parts of a JWT and say which claims a verifier must check and in what order, explain why a signed token cannot be recalled before it expires, describe refresh token rotation and reuse detection, tell the identity provider's single sign-on session from an app's own session, compare local sign-out, sign-out at the identity provider and back-channel logout, and choose idle and absolute timeouts. A TypeScript model lets you watch each of them happen on a virtual clock.

    Think of a festival. At the main gate your ticket is checked once and you get a wristband: that is single sign-on. Each stage lets you in on sight of the wristband, and a stage may also stamp your hand for its own records. If you scrub the stamp off at one stage, the gate still knows you, so walking back into that stage gets you a fresh stamp with no questions. If the gate cuts your wristband, the stages only find out if someone tells them, or the next time they check. And a day-pass printed with an end time stays valid until that time, whatever happens at the gate.

    "The user is signed in" is not one fact. It is several clocks, owned by different parties, that sign-out has to stop. The running example is the staff dashboard from the previous lesson, OAuth 2.0, OIDC and PKCE in Single-Page Apps, now with a second app, a support console, and an Orders API behind both. The names are made up, and every lifetime in this lesson is illustrative.

    The core idea

    1. A JWT is a signed bundle of claims, and it is believed only after a fixed set of checks. Reading the claims is not verifying them.
    2. Signed in is several clocks. An access token expires on its own clock, a refresh token is spent on use, the identity provider has an SSO session, and each app has its own session. They end at different times and for different reasons.
    3. Sign-out ends only what it is wired to end. A self-contained access token keeps working until it expires unless something checks a list, and an app session survives unless the app is told or it asks.

    What a JWT is, and how a verifier checks one

    RFC 7519 defines a JSON Web Token as a compact claims representation. In the compact form it is a sequence of URL-safe parts separated by period characters: a header, a payload of claims and a signature, for example header.payload.signature. The header names the algorithm. The payload is JSON claims. The signature covers the first two parts. The payload is encoded, not hidden: anyone holding the token can read the claims without a key (the lab prints a token's claims using a decoder that checks nothing).

    Claim Meaning Check
    iss who issued it equals the issuer you trust
    sub who it is about identifies the user
    aud who it is for your own identifier must be in it
    exp expiry, as seconds since 1970 now must be before it
    nbf not before now must be at or after it
    iat issued at informational, or a maximum age
    jti unique token id useful for denylists and logs
    sid session id (used in OpenID Connect logout tokens) ties the token to an SSO session

    RFC 7519 says that exp requires the current time to be before the expiry, that nbf requires the current time to be after or equal to the not-before time, and that implementers may allow a small leeway, usually no more than a few minutes, for clock skew. It also says that a JWT must be rejected if the processing party does not identify itself with a value in aud.

    The order of checks matters, and the lab runs them in this order: the structure, the algorithm, the signature, and only then the claims.

    Figure 1. Checks a verifier runs, in order

    flowchart TD accTitle: Order of checks when verifying a JWT accDescr: The verifier checks the token has three parts, that the header's algorithm is on its own allow-list, that the signature is valid, that exp is present and in the future, that nbf has passed, that the issuer is the expected one and that the audience contains its own identifier. Any failure rejects the token. A["Three parts, valid JSON?"] -->|"no"| X["Reject: malformed"] A -->|"yes"| B{"alg on MY allow-list?"} B -->|"no, including none"| X B -->|"yes"| C{"Signature valid
    for my key?"} C -->|"no"| X C -->|"yes"| D{"exp present and
    now before exp (+ skew)?"} D -->|"no"| X D -->|"yes"| E{"nbf passed (- skew)?"} E -->|"no"| X E -->|"yes"| F{"iss is the expected issuer?"} F -->|"no"| X F -->|"yes"| G{"aud contains my identifier?"} G -->|"no"| X G -->|"yes"| OK["Accept the claims"]

    How to read this: nothing in the payload is believed until the signature has passed, and the verifier decides which algorithms are acceptable, not the token.

    The algorithm rule comes from RFC 8725, the JWT best current practice. It names the attack: the algorithm in the header can be changed to none by an attacker, and some libraries would trust it (an Unsecured JWT, per RFC 7519, is one with alg set to none). Its answer is that libraries must let the caller specify the set of supported algorithms and must not use any other, and that each key must be used with exactly one algorithm. RFC 8725 also says the relying party must validate the audience, and recommends explicit typing through the typ header for new uses of JWTs. In the lab, a token with alg: none and one claiming HS384 are both refused as alg-not-allowed against an allow-list of one, and an ID Token sent to the API is refused as wrong-audience: the audience is what keeps the ID Token (for the app) apart from the access token (for the API).

    Clock skew

    Two machines never agree to the second, so verifiers allow a small leeway on both exp and nbf. Keep it small: skew is a grace period for a token that has already expired. The lab's demo checks a token valid from t=1000 to t=1100 at eight clocks, with no leeway and with 60 seconds.

    Illustrations

    Illustration 1 (minimal): one token, eleven verdicts

    The lab builds one valid token and ten damaged ones and prints the verdict for each: signed with another key, payload edited after signing, alg: none, an HS384 header, expired, not yet valid, wrong issuer, wrong audience, no exp, and a string that is not a JWT. Exactly one is accepted. The edited payload is rejected as bad-signature because the signature covers the payload.

    Illustration 2 (realistic): the dashboard, the console and the Orders API

    Both apps send users to one identity provider. Each gets an ID Token with its own identifier as aud and an access token with the Orders API as aud. The API verifies every call with the checks above and never calls the identity provider. That is the point of a self-contained token, and its cost, as the sign-out section shows.

    Illustration 3 (failure): signed out, still reading orders

    A user signs out at the identity provider. For the rest of the access token's life the Orders API still answers that token's calls, because the signature, exp, iss and aud are all still valid. Nothing in the token says the session ended.

    Refresh tokens: rotation and reuse detection

    Short access tokens need a way to renew without sending the user back to the sign-in page. A refresh token is issued to the client by the authorization server and exchanged for a new access token. RFC 6749 says the server may issue a new refresh token in the response, in which case the client must discard the old one, and that the requested scope must not exceed what the user originally granted.

    For public clients (browser apps), RFC 9700 and RFC 10017 go further: the server must either bind the refresh token to the client instance (sender-constrained) or rotate it, issuing a new refresh token with every refresh and invalidating the old one. With rotation, a spent token that is presented again is a signal that two parties hold the same token, and RFC 9700 says the server then revokes the active refresh token.

    Figure 2. Rotation, and what a replay costs

    sequenceDiagram accTitle: Refresh token rotation with reuse detection accDescr: The client refreshes with token one and receives token two. Later an attacker who copied token one presents it. The server sees a spent token, revokes the whole family including token two, and the honest client's next refresh with token two also fails, forcing a new sign-in. participant C as Client participant S as Authorization server participant A as Attacker C->>S: refresh with RT1 S-->>C: new access token + RT2 (RT1 is spent) A->>S: refresh with RT1 (copied earlier) S->>S: RT1 already used: revoke the family S-->>A: invalid_grant C->>S: refresh with RT2 S-->>C: invalid_grant (family revoked) Note over C: the user must sign in again

    How to read this: rotation does not stop the theft. It makes the theft visible the first time either side reuses a token, at the price of signing out the honest user too.

    The lab shows this exact sequence: a refresh at t=10250 returns a new token, the old one replayed later is reported as refresh token reuse detected, and the honest client's newest token then fails with refresh token family revoked.

    Single sign-on: one session at the provider, one per app

    Single sign-on (SSO) means the user authenticates once to the identity provider and then each app obtains tokens without a second password prompt. It works because the identity provider keeps its own SSO session (a cookie on its own origin), and each app starts its own app session from an ID Token. OpenID Connect Core gives the app ways to ask for what it needs: prompt=none makes the server show no sign-in or consent page and return an error such as login_required if the user is not already authenticated, prompt=login asks for re-authentication, and max_age limits how long ago the user was actively authenticated, in which case the ID Token must carry an auth_time claim.

    Figure 3. Two layers of session

    One SSO session at the identity provider, one app session per app, one APIDashboard to Identity provider (sign in, refresh); Support console to Identity provider (silent sign-in); Support console to Orders API (access token); Dashboard to Orders API (access token)Dashboard: app session ADashboardapp session ASupport console: app session BSupportconsoleapp session BIdentity provider: SSO sessionIdentityproviderSSO sessionOrders API: checks tokens onlyOrders APIchecks tokensonlysign in, refreshsilent sign-inaccess tokenaccess token

    How to read this: the identity provider holds the one session everything else derives from. The apps and the API keep their own state and know nothing about each other.

    Sign-out: three different things

    Kind What it ends What it leaves
    Local sign-out (one app) that app's session the SSO session, other apps, the access token until exp; reopening the app signs the user straight back in
    Sign-out at the identity provider (RP-initiated logout) the SSO session and its refresh tokens app sessions, unless the provider tells them
    Back-channel logout each notified app's session for that SSO session access tokens already issued, until they expire or a denylist is checked

    OpenID Connect RP-Initiated Logout lets an app send the user to the provider's logout endpoint with an id_token_hint, an optional post_logout_redirect_uri that must have been registered beforehand, and state. The provider should ask the user whether to log out of the provider as well. OpenID Connect Back-Channel Logout covers the other half: the provider sends an HTTP POST directly to each app's registered backchannel_logout_uri carrying a Logout Token, a JWT with iss, aud, iat, jti and an events claim, and either sub or sid (or both). A Logout Token must not contain a nonce, so it cannot be mistaken for an ID Token.

    RFC 7009 lets a client revoke a token, with the stated purpose that a client can invalidate its tokens if the user logs out. Revoking a refresh token should also invalidate the access tokens issued from the same grant when the server supports that. For self-contained access tokens it is blunt about the limit: immediate revocation needs some non-standardized interaction between the authorization server and the resource server, and otherwise the window is limited by issuing short-lived access tokens.

    Figure 4. What each action reaches

    flowchart TD accTitle: What each kind of sign-out reaches accDescr: Local sign-out ends only the app session. Sign-out at the identity provider ends the SSO session and revokes refresh tokens, and with back-channel logout also ends app sessions. The access token keeps working until it expires unless the API checks a denylist of ended sessions. L["Local sign-out"] --> A1["App session ends"] P["Sign out at the
    identity provider"] --> S["SSO session ends"] S --> R["Refresh tokens revoked"] S --> BC{"Back-channel logout
    registered?"} BC -->|"yes"| A2["App sessions end"] BC -->|"no"| A3["App sessions live on
    until their own timeouts"] R --> T{"API checks a
    denylist?"} T -->|"yes"| E1["Access token refused now"] T -->|"no"| E2["Access token works until exp"]

    How to read this: pick the action on the left and follow the arrows. The access token is the last thing to go unless the API takes on the work of checking.

    Timeouts: idle and absolute

    OWASP's Session Management Cheat Sheet says expiration timeouts are mandatory for every session and distinguishes two: an idle timeout, after no activity, and an absolute timeout, after a fixed time regardless of activity. It also says logout must invalidate the session at least on the server side. Both layers need them (the OWASP page is about web sessions; the same two timeouts apply to an app session and to an SSO session): the app session has its own pair, and the SSO session has another. The shortest one a user hits ends the visible session, and the lab demonstrates this with a session that is never idle for 100 seconds yet ends at its 250-second absolute limit.

    OWASP also says the session identifier must be renewed after any privilege change such as sign-in, to prevent session fixation: a new login must produce new tokens and a new app session.

    Build it: three clocks and two sign-outs

    Goal. Verify real signed tokens against damaged ones, rotate a refresh token and catch its replay, and run one SSO session with two apps through local sign-out and sign-out at the identity provider with and without back-channel logout.

    Setup. The lab is in the course's example workspace. It needs Node.js (captured on Node 26.13.1) and pnpm. It uses node:crypto HMAC for signatures, so the tokens are real but the keys are fake, and time is a number the script moves.

    cd examples/frontend
    pnpm install
    pnpm --filter ./labs/token-session-lifecycle test   # 32 tests
    cd labs/token-session-lifecycle
    node src/demo.ts

    Steps.

    1. In section 1 of the output, predict each verdict before reading it. The edited payload is a bad-signature, not expired, because the signature is checked first.
    2. In section 2, find the rows where 60 seconds of leeway accepts a token that no leeway rejects, and the last row where the leeway runs out.
    3. In section 3, follow rt-3 to rt-7 to rt-9 and see which call the replay of rt-3 damages.
    4. In section 4, compare the API's answers at t=10200 with and without the denylist lookup.
    5. In section 5, read both runs: local sign-out leaves the SSO session alive and reopening the app signs back in silently, and without back-channel logout both apps stay signed in after sign-out at the provider.

    Expected output, captured from a real run (Node 26.13.1, 2026-12-01):

    === 1. Validating a JWT: signature first, then algorithm, time, issuer, audience (now t=1000)
    claims of the valid token: {"iss":"https://id.example","sub":"user-1","aud":"https://api.shop.example","iat":900,"exp":1300}
    valid                          -> accepted
    signed with another key        -> rejected: bad-signature
    payload edited after signing   -> rejected: bad-signature
    alg none, no signature         -> rejected: alg-not-allowed
    header says HS384              -> rejected: alg-not-allowed
    expired (exp 990)              -> rejected: expired
    not yet valid (nbf 1100)       -> rejected: not-yet-valid
    wrong issuer                   -> rejected: wrong-issuer
    wrong audience (an ID Token)   -> rejected: wrong-audience
    no exp claim                   -> rejected: missing-exp
    not a JWT                      -> rejected: malformed
    
    === 2. Clock skew: a token valid from t=1000 up to t=1100, checked at eight verifier clocks, with 0 s and 60 s of leeway
    verifier clock t=939: skew 0 -> rejected: not-yet-valid    skew 60 -> rejected: not-yet-valid
    verifier clock t=940: skew 0 -> rejected: not-yet-valid    skew 60 -> accepted
    verifier clock t=999: skew 0 -> rejected: not-yet-valid    skew 60 -> accepted
    verifier clock t=1000: skew 0 -> accepted                   skew 60 -> accepted
    verifier clock t=1099: skew 0 -> accepted                   skew 60 -> accepted
    verifier clock t=1100: skew 0 -> rejected: expired          skew 60 -> accepted
    verifier clock t=1159: skew 0 -> rejected: expired          skew 60 -> accepted
    verifier clock t=1160: skew 0 -> rejected: expired          skew 60 -> rejected: expired
    
    === 3. Refresh token rotation and reuse detection
    t=10250 refresh with rt-3: new refresh token rt-7, new access token for the API
    t=10500 refresh with rt-7: new refresh token rt-9
    t=10500 someone replays the spent rt-3: refresh token reuse detected
    t=10500 the legitimate client then uses rt-9: refresh token family revoked
    revoking a token nobody issued: no error (revocation always answers success)
      idp: user-1 signed in, SSO session sid-1
      idp: tokens issued to shop-app for user-1 (sid sid-1)
      idp: refresh token reuse detected in fam-2, the whole family is revoked
    
    === 4. Sign-out and the access token that outlives it (access token lifetime 300 s, illustrative)
    t=10000 API call with the access token: 200
    t=10100 the user signs out at the identity provider
    t=10100 refresh attempt: {"ok":false,"error":"invalid_grant","detail":"refresh token family revoked"}
    t=10200 API, signature and claims only:   {"status":200,"detail":"ok for user-1"}
    t=10200 API, with a denylist lookup:      {"status":401,"detail":"session ended (found in the denylist)"}
    t=10300 API, signature and claims only:   {"status":401,"detail":"expired"}
    
    === 5. One SSO session, two apps: local sign-out versus signing out at the identity provider
    -- back-channel logout registered: true
      both apps signed in with no second password prompt: shop=true, support=true
      shop: local sign-out -> shop={"signedIn":false,"reason":"ended by local sign-out"}, support=true
      shop: open the app again -> signed back in with no prompt: true
      sign out at the identity provider -> shop=false, support=false
      open shop once more -> {"ok":false,"reason":"login_required: session ended"}
    -- back-channel logout registered: false
      both apps signed in with no second password prompt: shop=true, support=true
      shop: local sign-out -> shop={"signedIn":false,"reason":"ended by local sign-out"}, support=true
      shop: open the app again -> signed back in with no prompt: true
      sign out at the identity provider -> shop=true, support=true
      open shop once more -> {"ok":false,"reason":"login_required: session ended"}
    
    === 6. Timeouts: idle and absolute (app idle 100 s, app absolute 250 s, illustrative)
    + 90 s: {"signedIn":true,"sub":"user-1"}
    +180 s: {"signedIn":true,"sub":"user-1"}
    +270 s: {"signedIn":false,"reason":"absolute timeout reached"}
    a fresh session left alone for 100 s: {"signedIn":false,"reason":"idle timeout reached"}

    What the lab does not show. No browser, cookies or network, and no real identity provider: logout notifications are plain function calls, so delivery failures and retries are not modelled. HMAC is used for signatures to stay inside node:crypto and keep output deterministic, whereas a provider would normally sign with a key pair so that APIs hold only a public key. Every lifetime is an illustrative choice.

    Break it. In src/jwt.ts, in verify, change if (o.now >= claims.exp + o.skewSeconds) to if (o.now > claims.exp + o.skewSeconds). A token is now accepted for one extra second, at the exact exp, and the tests about the expiry boundary and skew fail. Revert it.

    Stretch. Add a typ check so an ID Token cannot reach the API even with the audience fixed, or let the API cache its denylist for a few seconds and measure on the virtual clock how long a signed-out token still works.

    Choosing

    How quickly sign-out must take effect is a business question: how long may a signed-out user still read data? The mechanisms follow from the answer.

    Choice Gain Cost
    Short access tokens, no denylist no state at the API; sign-out ends within the lifetime the window after sign-out equals the remaining lifetime
    Denylist of ended sessions at the API immediate refusal state, a feed from the provider, a lookup per call
    Rotating refresh tokens replay is detected signs the honest user out too; clients must serialize refreshes
    Back-channel logout all apps end together each app needs an endpoint and a session index by sid
    Long SSO session fewer prompts a signed-out app can sign back in silently while it lasts
    Short absolute timeout bounds a stolen session more sign-ins for users

    In practice: a shared support desk

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A support team shares workstations. Agents sign in to the support console through the company identity provider and press "Sign out" at the end of a shift. The console is a web app with its own session cookie and calls the Orders API with an access token. Access tokens last five minutes (illustrative), and the identity provider's SSO session lasts eight hours (illustrative).

    Starting architecture

    Figure 5. Starting point: local sign-out only

    Starting architecture: Sign out in the console ends the console's session and nothing elseAgent browser to Console (Sign out); Agent browser to Identity provider (cookie remains)Agent browser: two cookiesAgent browsertwo cookiesConsole: ends own sessionConsoleends own sessionIdentity provider: SSO session staysIdentityproviderSSO session staysSign outcookie remains

    How to read this: the sign-out button stops at the console. The identity provider never hears about it and its cookie stays in the browser.

    Options considered

    Option What it fixes What it costs Risk
    Shorten the SSO session smaller window more sign-ins for everyone does not close the gap
    RP-initiated logout plus back-channel logout sign-out ends the SSO session and every app an endpoint in each app, a session index by sid needs testing across apps
    prompt=login on every sign-in each sign-in asks for credentials a prompt each time users dislike it; does not fix the sign-out

    The decision

    Field Decision record
    Context Shared workstations, a console that signs out locally, an SSO session that outlives the shift.
    Decision "Sign out" calls RP-initiated logout, the console registers a back-channel logout endpoint and stores sid with each session, refresh tokens are revoked at logout, and the Orders API stays stateless with five-minute tokens.
    Consequences, good The next agent has to authenticate, other apps end together, and exposure after logout is bounded by the token lifetime.
    Consequences, bad Signing out of one app signs the user out of all, and a failed logout notification leaves an app session until its own timeout.
    Revisit when Five minutes of continued API access is too long for a data class. Then add a denylist or introspection at the API.

    Rollout and verification

    1. Test the whole chain with two apps and one SSO session: sign in to both, sign out of one, and confirm both end.
    2. Test the failure path: stop one app's logout endpoint and confirm it still ends at its own timeout.
    3. Add a synthetic check that signs in, signs out and attempts a silent sign-in, expecting login_required.
    4. Watch the count of silent sign-ins that succeed after a logout.

    The 2 a.m. failure

    A manager reports that a second agent opened the console on a shared workstation and saw the previous agent's name and queue without signing in. The console's cookie had been cleared by "Sign out", but opening the console started a login redirect, the identity provider still had its SSO session, and it returned tokens at once: a silent sign-in.

    First three checks: (1) check what the sign-out button does: only the console session, or the provider's logout endpoint; (2) look at the provider's session list for the user after sign-out; (3) check whether the console starts login with a request that reuses the SSO session. Mitigation: call the provider's logout endpoint from the button and shorten the SSO idle timeout on shared workstations. Follow-up: register back-channel logout, require max_age for sensitive actions, and add the synthetic check above.

    Architect's notes

    • Keep access tokens short and refresh tokens rotating, then set the sign-out window from the data's sensitivity.
    • Verify, do not decode. Use a library with an explicit algorithm allow-list, and pin the issuer and audience in configuration.
    • Index app sessions by sid, so a Logout Token can find and end them.
    • Name the four clocks (access token, refresh token, SSO session, app session) and write down the longest time a signed-out user could still act.
    • Test sign-out across two apps, not one. The bugs live between them.

    Common mistakes

    • Decoding a JWT and trusting its claims without verifying the signature, issuer and audience.
    • Letting the token choose its algorithm, or accepting none.
    • Skipping the audience check, so an ID Token works as an access token.
    • Using a large clock-skew allowance to hide a clock problem.
    • Expecting sign-out to recall an access token. A self-contained token works until exp.
    • Building "sign out" as a local action only, so the next visitor is signed in silently.
    • Sharing one refresh token across tabs with rotation on, so two tabs race and trigger reuse detection.

    Key takeaways

    • A JWT is header.payload.signature. The payload is readable by anyone, and trusted only after the algorithm, signature, exp, nbf, iss and aud checks.
    • The verifier owns the algorithm allow-list. alg: none and unlisted algorithms are refused.
    • exp means now must be before it, nbf means now must be at or after it, and skew is a small leeway on both ends.
    • Rotating refresh tokens detect replay but sign the honest client out as well.
    • SSO is one provider session plus one session per app. A local sign-out in one app leaves the rest.
    • Back-channel logout and revocation end sessions and refresh tokens, but a self-contained access token lives until it expires unless the API checks a list.
    • Use idle and absolute timeouts, enforced on the server, at every layer.

    Practice exercises

    Exercise 1 — Starter (30 min): For each of the eleven tokens in section 1 of the demo output, write which check in Figure 1 rejects it, and which check would have caught it if the signature check were removed.

    Exercise 2 — Intermediate (2 hours): Add a test where two tabs hold the same refresh token and both refresh. Predict who is signed out, then run it. Write the client rule (a lock around refresh) that would prevent it, and name the browser feature you would use. See the lesson on cross-tab synchronization.

    Exercise 3 — Advanced (half day): Extend the lab so the API feeds on a periodic list of ended sessions with a five-second delay. Measure on the virtual clock how long a signed-out token works, and write a one-page note for the security team on whether the delay is acceptable.

    In this course:

    Elsewhere on the site:

    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