TL;DR
- A signed JWT can be verified without a database lookup, but that also means its issuer cannot instantly invalidate a copy that is already in a client’s hands.
- Short-lived access tokens limit that exposure window. A server-side refresh-session record supports logout, device-level revocation, absolute expiry, and refresh-token rotation.
- Store a cryptographically random opaque refresh token in a server-scoped,
HttpOnly; Securecookie. Persist only a one-way verifier and rotate the token atomically on every successful refresh. - If a previously consumed refresh token appears again, treat it as possible replay. Revoke its token family, alert safely, and require a new authorization flow. Design for legitimate concurrent refreshes and lost responses too.
- Cookie-based refresh endpoints need a CSRF strategy.
SameSitehelps, but its correct setting depends on the authentication flow and site boundaries.
The gap between a valid JWT and a revocable session
A JSON Web Token (JWT) is a signed set of claims. A resource server can validate the signature, issuer, audience, and expiry without contacting the system that issued it. That makes request verification convenient across services, but a self-contained token has no built-in live connection to the user’s current account state. If an administrator disables an account, the signature on a JWT already issued remains valid until its expiry unless each request checks additional server-side state.
There are three common ways to handle this tradeoff. Keep access tokens short-lived and accept a bounded revocation delay. Check a session or account version on every request, which makes authorization depend on a server-side lookup or cache. Or use opaque, server-side sessions so revocation is a direct state change. These models can be combined. A short-lived signed access token plus a revocable refresh session keeps most API calls local while providing a control point for future tokens.
The word “instant” needs a precise boundary. Revoking a refresh family prevents that family from minting new access tokens after the revocation becomes visible. It does not erase a JWT already copied by an attacker. That access token remains usable until it expires unless resource servers check a revocation list, session state, or another authorization signal on each request. OWASP FastAPI security guidance
Model sessions and refresh-token families explicitly
Keep one session family for each browser or device authorization. A user who signs in on a laptop and a phone should have separate revocation handles. A session record can contain an internal session ID, user ID, client or device label, current token verifier, creation time, last-used time, idle expiry, absolute expiry, revocation time, and a monotonically increasing generation. Never trust a client-provided device label as a security attribute.
Represent each refresh token as an opaque random secret. The cookie carries the secret; the database stores a verifier such as SHA-256 of its high-entropy bytes, along with the family, generation, expiry, and consumption state. A keyed HMAC can add protection if database-only disclosure is a concern, provided key management and rotation are planned. Password hashing is usually unnecessary for randomly generated tokens with ample entropy because they are not human-chosen passwords.
Use an unambiguous token identifier or family identifier only as a lookup hint. The secret is the proof. A split cookie format such as session_id.secret can locate the session without storing or indexing the raw secret, but an attacker must still present the valid secret. Store neither raw refresh values in logs nor recoverable copies in analytics or exception traces.
Make the token family the unit of revocation. “Log out this device” revokes one family. “Log out everywhere,” password reset, account recovery, or suspected compromise can revoke every active family for the user. Keep an audit event containing the reason and actor, not the credential that triggered it.
Rotate the refresh token in one transaction
Rotation means a successful refresh consumes the presented token and issues a different one. The old token must not be reusable. For public OAuth clients, current OAuth security guidance requires refresh-token replay detection through sender-constrained refresh tokens or refresh-token rotation. Rotation retains the relationship between old and new tokens so a reused predecessor can identify the affected grant. The server generally cannot tell whether the legitimate client or an attacker presented that old value, so revoking the active family is a deliberate security response. RFC 9700 refresh-token protection
A safe refresh handler follows a narrow sequence:
- Read the cookie and resolve its verifier to one active family.
- Start a database transaction and lock the family or current token row.
- Check revocation, idle expiry, absolute expiry, user status, client binding, and token consumption.
- If the token is active, mark it consumed and insert the next verifier and generation before committing.
- Return a new short-lived access token and set the replacement refresh cookie only after the transaction succeeds.
BEGIN;
SELECT family_id, generation, consumed_at, revoked_at, idle_expires_at,
absolute_expires_at
FROM refresh_session
WHERE token_hash = :presented_hash
FOR UPDATE;
-- Application verifies expiry, family status, user status, and CSRF policy.
-- If active, consume the old row and add the next token verifier.
UPDATE refresh_session
SET consumed_at = transaction_timestamp()
WHERE token_hash = :presented_hash
AND consumed_at IS NULL
AND revoked_at IS NULL;
INSERT INTO refresh_session (
token_hash, family_id, generation, idle_expires_at, absolute_expires_at
) VALUES (
:next_hash, :family_id, :next_generation, :next_idle_expiry, :absolute_expiry
);
COMMIT;
The SQL is illustrative. In a real schema, enforce one active generation per family, check that the conditional update affected exactly one row, and make user disablement and family revocation visible to this transaction. A database uniqueness constraint can prevent two replacements from being created for the same generation. Keep the transaction short and never call an external identity provider while holding its row lock.
Detect replay without mistaking every race for theft
When a consumed token is presented again, the server has evidence of reuse. Revoke the family, invalidate its active refresh token, and require reauthentication. If the token is unknown or expired, return a generic authentication failure without revealing whether a particular account exists. Emit a security event with a correlation ID and family ID, but do not log the token or cookie header.
There is a legitimate race to plan for. A browser may send refresh requests from two tabs at nearly the same time. A mobile client may retry after the server committed rotation but the response was lost. With strict one-use semantics, the second request presents a consumed token and looks exactly like replay. Serialize refreshes in the client, use a single-flight refresh coordinator, and treat refresh as a critical operation with carefully defined retry behavior.
Some systems keep an encrypted, brief response record to recover from a network retry. That design must bind the retry to the same request and client context, limit the recovery window, avoid storing reusable secrets in plaintext, and preserve detection for requests that do not match. It is a security tradeoff, not a free extension to token validity. For high-risk OAuth clients, sender-constraining can reduce the value of a stolen bearer token, but it adds key lifecycle and client support requirements. RFC 9449 DPoP
Do not add a generous grace period without a threat model. During grace, a stolen previous token may still be accepted. If you permit overlap, distinguish harmless parallelism from replay using a client-held proof, sender constraint, or narrowly scoped idempotent exchange record. Document the residual risk and test it under parallel requests and lost responses.
Choose browser storage and cookie attributes for the app
For a browser application, avoid putting long-lived refresh credentials in localStorage or sessionStorage. JavaScript executing in the page’s origin can read those values, so a cross-site scripting flaw can extract them. An HttpOnly cookie prevents page JavaScript from reading the cookie, while the browser still sends it with matching requests. Use Secure so it is sent only over HTTPS and choose the narrowest practical host, path, and lifetime. OWASP recommends secure cookie attributes and advises against browser storage for authentication tokens. OWASP session cookie guidance
Set-Cookie: __Host-refresh=opaque-random-value;
Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=1209600
SameSite=Strict can block the cookie in cross-site navigation flows that a product may rely on. Lax is often a workable baseline for same-site applications, while None requires Secure and makes explicit CSRF controls especially important. Choose based on the actual frontend and identity-provider flow. The __Host- prefix requires a secure origin, Path=/, and no Domain attribute in supporting browsers. MDN Set-Cookie reference
Cookies are attached by the browser, so state-changing refresh or logout endpoints need CSRF protection. Validate an anti-CSRF token or another defensible same-origin mechanism, check Origin where appropriate, and configure CORS to allow only known origins with credentials. CORS is not a replacement for CSRF protection. A Backend-for-Frontend (BFF) can keep OAuth tokens server-side and expose a same-origin session cookie to the browser.
For native clients, do not pretend browser cookie rules apply. Use platform-protected credential storage, bind refresh tokens to the intended client where available, and define revocation behavior for lost devices.
Revoke sessions on meaningful security events
Expose session management so a user can see and revoke active devices. A logout endpoint should revoke the current family server-side and clear the browser cookie with the same path and attributes used to create it. Clearing only the cookie leaves a stolen copy active. An account-wide action should revoke all family records and may advance a user-level session version.
Decide which events revoke what. Password change, recovery, administrator disablement, suspected account takeover, or organization membership removal may revoke all sessions. A user signing out of one device should usually revoke only that family. If a product has multiple services, define how revocation propagates and how long caches may delay enforcement.
If access JWTs are validated without server state, their expiry is the maximum ordinary revocation delay. Keep that lifetime short enough for the product’s risk, but not so short that every request triggers continuous refresh. If the resource server checks a user or session version, cache it with an explicit freshness limit. “Instant” then means the configured propagation and cache invalidation behavior, not a property of JWT itself.
OAuth token revocation has a standard endpoint for clients to tell an authorization server that a token is no longer needed. RFC 7009 describes that protocol and its response semantics. It does not revoke copies issued by an unrelated JWT system unless that system participates in the revocation design. RFC 7009 token revocation
Test the security and failure boundaries
- Refresh once, then confirm the prior token cannot mint another access token.
- Replay a consumed token and confirm the active family is revoked and a safe security event is emitted.
- Send two concurrent refreshes and verify the documented race outcome is consistent.
- Drop the HTTP response after the server commits rotation, then exercise the client’s retry path.
- Revoke one device and confirm another device family remains active.
- Change a password or disable an account and verify the intended families and access tokens are invalidated within the documented window.
- Send a forged cross-site refresh request and verify CSRF defenses reject it.
- Check cookies on HTTPS and localhost, across supported browsers, and with the production proxy and domain configuration.
- Search logs, traces, metrics, and error reports for raw refresh tokens, cookies, authorization headers, and personal data.
Keep telemetry useful but credential-safe. Record family identifiers, token generation, outcome category, and request correlation ID. Avoid IP-based “theft detection” as a sole signal because addresses change, users travel, and networks are shared. A new IP can increase risk or request step-up authentication, but it is not proof that a refresh token was stolen.
Frequently asked questions
Can a JWT be revoked instantly after logout?
Not if the resource server validates only its signature and expiry. A copied JWT remains valid until expiration. Immediate enforcement requires a server-side revocation or session check, short cache propagation, or an opaque session model. Short access-token lifetimes bound the exposure window but do not remove it.
What should happen when an old refresh token is reused?
Treat reuse of a known consumed token as possible replay, revoke the token family, and require a fresh authorization. Also design for legitimate parallel refreshes and lost responses, which can present the same predecessor. Serialize client refreshes or use a narrowly scoped, security-reviewed recovery strategy.
Should a refresh token be stored in localStorage?
No for a browser app. JavaScript running in the origin can read localStorage, so an XSS flaw can extract the token. Prefer a server-held token or an HttpOnly, Secure cookie with an appropriate SameSite setting and CSRF protection for state-changing endpoints.
Does SameSite=Strict work for every sign-in flow?
No. Strict cookies may be withheld on cross-site navigations used by some authentication callbacks. Test the real browser and identity-provider flow. Lax may fit many same-site applications; None requires Secure and stronger explicit CSRF protections.
Make revocation behavior an explicit contract
Rotating refresh tokens add a server-side session boundary to short-lived JWTs. Persist token verifiers and family state, serialize rotation in a transaction, and treat a consumed token presented again as a security event. Pair that design with secure storage, CSRF protection, session expiry, and a clear plan for lost responses and concurrent browser tabs.
Document exactly what “logout,” “revoke this device,” and “revoke all sessions” mean for both refresh credentials and already-issued access tokens. If you are reviewing a FastAPI authentication flow, talk with our security engineers about the token lifecycle, browser boundary, and revocation window.
