Secure JWT Refresh Token Rotation with Python
Implement secure JWT access and refresh token rotation in Python with blacklist, reuse detection, and automatic access token renewal for stateless auth
Overview
JWT access tokens stay short-lived (15-30 minutes) to shrink the window of exposure if one gets stolen. Refresh tokens live longer, but leaving them reusable is a replay-attack gift — so each use should issue a new refresh token and invalidate the old one. That’s rotation.
This recipe builds a TokenManager that rotates refresh tokens, keeps a blacklist for replay protection, and detects reuse so you can treat a stolen token as a full-session compromise. It plugs into FastAPI, and there’s a Redis-backed variant for multi-instance deployments. If you want the broader auth picture — OAuth flows, session cookies, password policies — the complete authentication patterns guide covers it. For the Node.js side of JWT auth, see Node.js JWT authentication.
When to Use This
- Stateless APIs that can’t afford a server-side session store for every request
- Mobile apps or SPAs where users stay logged in for days or weeks
- Any system where access tokens expire frequently and clients must renew silently
Skip this recipe if your app is a classic server-rendered web app with one backend — a plain session cookie is simpler to revoke and audit.
Prerequisites
- Python 3.10+
pyjwtpackage (pip install pyjwt)cryptographyfor RS256 support (optional)fastapiif you want to run the API example (pip install fastapi uvicorn)
Solution
1. Install Dependencies
pip install pyjwt
2. Token Manager
import jwt
import time
import uuid
import secrets
from dataclasses import dataclass
@dataclass
class TokenPair:
access_token: str
refresh_token: str
access_expires_at: int
refresh_expires_at: int
class TokenManager:
def __init__(
self,
secret_key: str,
access_token_ttl: int = 900, # 15 minutes
refresh_token_ttl: int = 604800, # 7 days
algorithm: str = "HS256",
):
self.secret_key = secret_key
self.access_token_ttl = access_token_ttl
self.refresh_token_ttl = refresh_token_ttl
self.algorithm = algorithm
self._blacklist: set[str] = set()
self._active_refresh_tokens: dict[str, dict] = {}
def generate_tokens(self, user_id: str, claims: dict | None = None) -> TokenPair:
"""Generate a new access and refresh token pair.
Args:
user_id: User identifier.
claims: Additional claims to include in the access token.
Returns:
TokenPair with both tokens and expiry timestamps.
"""
now = int(time.time())
access_jti = str(uuid.uuid4())
refresh_jti = str(uuid.uuid4())
access_payload = {
"sub": user_id,
"jti": access_jti,
"type": "access",
"iat": now,
"exp": now + self.access_token_ttl,
**(claims or {}),
}
refresh_payload = {
"sub": user_id,
"jti": refresh_jti,
"type": "refresh",
"iat": now,
"exp": now + self.refresh_token_ttl,
}
access_token = jwt.encode(access_payload, self.secret_key, algorithm=self.algorithm)
refresh_token = jwt.encode(refresh_payload, self.secret_key, algorithm=self.algorithm)
self._active_refresh_tokens[refresh_jti] = {
"user_id": user_id,
"expires_at": now + self.refresh_token_ttl,
}
return TokenPair(
access_token=access_token,
refresh_token=refresh_token,
access_expires_at=now + self.access_token_ttl,
refresh_expires_at=now + self.refresh_token_ttl,
)
def verify_access_token(self, token: str) -> dict | None:
"""Verify an access token and return its payload.
Args:
token: JWT access token.
Returns:
Token payload dict or None if invalid/expired.
"""
try:
payload = jwt.decode(
token,
self.secret_key,
algorithms=[self.algorithm],
)
if payload.get("type") != "access":
return None
if payload["jti"] in self._blacklist:
return None
return payload
except jwt.ExpiredSignatureError:
return None
except jwt.InvalidTokenError:
return None
def rotate_refresh_token(self, refresh_token: str) -> TokenPair | None:
"""Rotate a refresh token — issue a new pair and invalidate the old one.
Args:
refresh_token: The current refresh token.
Returns:
New TokenPair or None if the token is invalid/reused/blacklisted.
"""
try:
payload = jwt.decode(
refresh_token,
self.secret_key,
algorithms=[self.algorithm],
)
except (jwt.ExpiredSignatureError, jwt.InvalidTokenError):
return None
if payload.get("type") != "refresh":
return None
jti = payload["jti"]
user_id = payload["sub"]
if jti in self._blacklist:
return None
if jti not in self._active_refresh_tokens:
return None
del self._active_refresh_tokens[jti]
self._blacklist.add(jti)
return self.generate_tokens(user_id)
def revoke_refresh_token(self, refresh_token: str) -> bool:
"""Revoke a refresh token (logout).
Args:
refresh_token: The refresh token to revoke.
Returns:
True if a valid refresh token was revoked.
"""
try:
payload = jwt.decode(
refresh_token,
self.secret_key,
algorithms=[self.algorithm],
)
except (jwt.ExpiredSignatureError, jwt.InvalidTokenError):
return False
if payload.get("type") != "refresh":
return False
jti = payload["jti"]
if jti in self._active_refresh_tokens:
del self._active_refresh_tokens[jti]
self._blacklist.add(jti)
return True
def revoke_all_user_tokens(self, user_id: str) -> int:
"""Revoke all refresh tokens for a user (password change, security breach).
Returns:
Number of tokens revoked.
"""
revoked = 0
to_remove = [
jti for jti, data in self._active_refresh_tokens.items()
if data["user_id"] == user_id
]
for jti in to_remove:
del self._active_refresh_tokens[jti]
self._blacklist.add(jti)
revoked += 1
return revoked
3. FastAPI Integration
from fastapi import FastAPI, HTTPException, Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
app = FastAPI()
token_manager = TokenManager(secret_key=secrets.token_urlsafe(32))
security = HTTPBearer()
def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)) -> dict:
"""Dependency to extract and verify the access token."""
payload = token_manager.verify_access_token(credentials.credentials)
if payload is None:
raise HTTPException(status_code=401, detail="Invalid or expired token")
return payload
@app.post("/auth/login")
def login(user_id: str = "user123"):
"""Login endpoint — returns access and refresh tokens."""
pair = token_manager.generate_tokens(user_id)
return {
"access_token": pair.access_token,
"refresh_token": pair.refresh_token,
"token_type": "Bearer",
"expires_in": token_manager.access_token_ttl,
}
@app.post("/auth/refresh")
def refresh(refresh_token: str):
"""Refresh endpoint — rotate refresh token and issue new access token."""
pair = token_manager.rotate_refresh_token(refresh_token)
if pair is None:
raise HTTPException(status_code=401, detail="Invalid or reused refresh token")
return {
"access_token": pair.access_token,
"refresh_token": pair.refresh_token,
"token_type": "Bearer",
"expires_in": token_manager.access_token_ttl,
}
@app.post("/auth/logout")
def logout(refresh_token: str):
"""Logout endpoint — revoke the refresh token."""
success = token_manager.revoke_refresh_token(refresh_token)
if not success:
raise HTTPException(status_code=400, detail="Invalid refresh token")
return {"message": "Logged out successfully"}
@app.get("/protected")
def protected_route(user: dict = Depends(get_current_user)):
"""Protected route requiring a valid access token."""
return {"user_id": user["sub"], "message": "Access granted"}
How It Works
The rotation contract, step by step:
- Access token is short-lived (15 min) and stateless — the server verifies signature and expiry, nothing more. No lookup per request.
- Refresh token is long-lived (7 days) but stateful — every issued refresh
jtiis tracked in_active_refresh_tokens, so the server knows which ones are still valid. - Rotation: when a refresh token comes in, it’s removed from the active set, added to the blacklist, and a fresh pair goes out. Each refresh token is single-use.
- Reuse detection: if a blacklisted
jtishows up again,rotate_refresh_tokenreturnsNone. In production that’s your theft signal — log it, alert, and callrevoke_all_user_tokensbecause either the user or an attacker is replaying. - Blacklist blocks replay attacks. An in-memory set works for demos; production needs Redis (or a DB) with TTL so entries expire with the tokens and all instances share state.
A few trade-offs worth knowing before you ship this:
- Grace periods: with strict single-use rotation, two concurrent requests carrying the same refresh token (common with mobile clients retrying on flaky networks) race each other — the second one gets rejected and looks like theft. Real-world implementations (Auth0, for example) allow a short reuse interval of a few seconds. You can add one by storing the time the token was consumed instead of deleting it immediately.
- Access token revocation: this design only blacklists refresh tokens. A stolen access token stays valid until it expires — that’s the price of stateless verification, and it’s why the 15-minute TTL matters. If you need instant access-token kill, you’re back to checking a store on every request, which defeats the point of JWT.
- Clock skew:
pyjwtaccepts aleewayparameter (e.g.jwt.decode(token, key, algorithms=[alg], leeway=30)) to tolerate a few seconds of drift between your server and whoever issued the token. Add it if you see sporadic “expired” rejections in multi-instance setups. - Where the client keeps the refresh token: for browser apps, prefer an
HttpOnly,Secure,SameSite=Strictcookie overlocalStorage—localStorageis readable by any injected script and turns a single XSS into account takeover. Mobile apps can keep it in the OS secure store (Keychain / Keystore).
Variants
Redis-Backed Blacklist
import redis
import json
class RedisTokenManager(TokenManager):
def __init__(self, *args, redis_url: str = "redis://localhost:6379", **kwargs):
super().__init__(*args, **kwargs)
self.redis = redis.from_url(redis_url)
def _blacklist_token(self, jti: str, expires_at: int) -> None:
ttl = max(expires_at - int(time.time()), 1)
self.redis.setex(f"blacklist:{jti}", ttl, "1")
def _is_blacklisted(self, jti: str) -> bool:
return bool(self.redis.exists(f"blacklist:{jti}"))
def _store_active(self, jti: str, user_id: str, expires_at: int) -> None:
ttl = max(expires_at - int(time.time()), 1)
self.redis.setex(f"refresh:{jti}", ttl, json.dumps({"user_id": user_id}))
def _is_active(self, jti: str) -> bool:
return bool(self.redis.exists(f"refresh:{jti}"))
Wire the helpers into generate_tokens, rotate_refresh_token and revoke_refresh_token so active/blacklist checks hit Redis instead of the in-memory structures — every instance then shares the same token state, and entries self-expire with the token TTL.
RS256 with Key Pair
from cryptography.hazmat.primitives import serialization
# Generate key pair
from cryptography.hazmat.primitives.asymmetric import rsa
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()
private_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
public_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
)
# Sign with private key, verify with public key
token = jwt.encode(payload, private_pem, algorithm="RS256")
payload = jwt.decode(token, public_pem, algorithms=["RS256"])
With RS256 your auth service is the only component holding the private key; every other service verifies with the public key, so a leaked verifier config can’t mint tokens. It also makes key rotation feasible — publish the public keys as a JWKS endpoint and rotate signers without downtime.
Automatic Refresh on 401 (Client-Side)
async function apiCall(url, options = {}) {
let response = await fetch(url, {
...options,
headers: { ...options.headers, Authorization: `Bearer ${getAccessToken()}` },
});
if (response.status === 401) {
const newTokens = await refreshTokens();
if (newTokens) {
response = await fetch(url, {
...options,
headers: { ...options.headers, Authorization: `Bearer ${newTokens.access_token}` },
});
}
}
return response;
}
One gotcha in production: concurrent calls can all hit the 401 branch and race to refresh. Queue the refresh promise (refreshPromise ??= refreshTokens()) so every waiting call reuses the same rotation instead of triggering your own reuse detection.
Best Practices
- Keep access tokens short-lived — 15-30 minutes is standard; shorter is safer since they can’t be revoked without a lookup
- Rotate refresh tokens on every use — single-use refresh tokens kill replay attacks
- Detect reuse and revoke the whole family — a blacklisted token showing up again means someone’s copy leaked; revoke all of the user’s tokens
- Use RS256 in production — asymmetric signing lets verifiers check tokens without holding the signing secret
- Store refresh tokens in HttpOnly cookies for web apps — keeps them out of reach of injected scripts
- Add a reuse grace interval — a few seconds of tolerance prevents false theft alarms from concurrent client retries
Common Mistakes
- Long-lived access tokens — the whole model falls apart if access tokens live for days; keep them short and lean on refresh
- Not rotating refresh tokens — a reusable refresh token is a permanent key sitting on every device the user owns
- Storing tokens in localStorage — readable by any XSS payload; use HttpOnly cookies on the web or the OS secure store on mobile
- Ignoring 401 on the client — if your client doesn’t auto-refresh on 401, users get randomly logged out mid-session
- Blacklist without TTL — blacklist entries that never expire grow forever; set the entry TTL to the token’s remaining lifetime
Further Reading
- PyJWT documentation — encode/decode options, leeway, algorithm support
- RFC 7519 — JSON Web Token — the JWT spec: claims, jti, validation rules
The complete runnable project — token_manager.py plus a FastAPI app with login/refresh/logout — is in the companion repository.
Frequently Asked Questions
Should I store refresh tokens in a database?
For a single-server app, in-memory is fine while you prototype. For anything distributed, use Redis with TTL — the blacklist and the active set must be shared across all instances, or rotation state drifts.
What happens if the user's refresh token is stolen?
Rotation limits the damage. When the legitimate user refreshes, the attacker's copy dies; if the attacker refreshes first, the user's copy dies — and the next use of the dead token triggers reuse detection. Either way, the theft surfaces fast, which is the whole point of rotating.
Should I use JWT or server-side sessions?
JWT for stateless, distributed APIs where a per-request lookup is too expensive. Server-side sessions for a single-backend web app — revocation and audit are simpler, and you don't need any of this machinery.
How do I handle token revocation with JWT?
You can't revoke a JWT itself — it's self-contained. Keep access tokens short-lived so they die on their own, and maintain a blacklist only for refresh tokens, which are the ones that mint new access tokens.
What if two requests try to rotate the same refresh token at once?
The second one sees a blacklisted jti and gets rejected — correct for theft, annoying for legitimate retries. Mobile clients hit this on flaky networks. Add a grace interval of a few seconds if false positives bother your users.
Where should the client store the refresh token?
Web apps: an HttpOnly, Secure, SameSite=Strict cookie — never localStorage, which any injected script can read. Mobile apps: the OS keychain or keystore. The goal is keeping it out of reach of JavaScript you don't control.
Do I need to blacklist access tokens too?
Usually no — that's what the 15-minute TTL is for. A stolen access token dies quickly on its own. Blacklisting access tokens means a store lookup on every request, which throws away the statelessness that made JWT attractive.
Related Resources
Node.js JWT Authentication: Verify and Refresh Tokens
Implement JWT authentication in Node.js: access and refresh tokens, rotation with reuse detection, and Express middleware
RecipeImplement Secure Session Management
How to create, validate, and expire user sessions securely using HTTP-only cookies, server-side stores like Redis, and CSRF protection.
RecipeManage Application Secrets with HashiCorp Vault and Python
Store, retrieve, and rotate application secrets securely using HashiCorp Vault with Python hvac client, dynamic secrets, and automatic lease renewal.
RecipeDistributed Rate Limiting with FastAPI and Redis
Implement distributed rate limiting in FastAPI using Redis sliding window and token bucket algorithms with per-user, per-IP, and per-endpoint limits.
RecipePrevent SQL Injection with SQLAlchemy Parameterized Queries
Protect Python applications from SQL injection using SQLAlchemy parameterized queries, ORM models, input validation, and query inspection to ensure safe database access
RecipeSecure API Gateway with Custom Lambda Authorizers
Implement custom Lambda authorizers for API Gateway with JWT validation, IAM policy generation, and caching for token-based authentication in serverless APIs.