FastAPI JWT Refresh Token Rotation
Issue short-lived access tokens plus rotating refresh tokens in FastAPI, detecting reuse of revoked tokens on every exchange.
Code
from datetime import datetime, timedelta, timezone
import jwt
from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel
SECRET = 'rotate-me-in-production'
REFRESH_TTL = timedelta(days=14)
ACCESS_TTL = timedelta(minutes=15)
app = FastAPI()
oauth2 = OAuth2PasswordBearer(tokenUrl='/token')
revoked: set[str] = set() # 生产环境应持久化并设置过期
class TokenPair(BaseModel):
access: str
refresh: str
def issue_tokens(user_id: str) -> TokenPair:
now = datetime.now(timezone.utc)
return TokenPair(
access=jwt.encode(
{'sub': user_id, 'exp': now + ACCESS_TTL, 'typ': 'access'},
SECRET, algorithm='HS256'),
refresh=jwt.encode(
{'sub': user_id, 'exp': now + REFRESH_TTL, 'typ': 'refresh',
'jti': f'{user_id}-{int(now.timestamp())}'},
SECRET, algorithm='HS256'),
)
@app.post('/token/refresh', response_model=TokenPair)
def refresh(pair: TokenPair):
try:
claims = jwt.decode(pair.refresh, SECRET, algorithms=['HS256'])
except jwt.InvalidTokenError:
raise HTTPException(401, 'invalid refresh token')
if pair.refresh in revoked:
raise HTTPException(401, 'token reuse detected')
revoked.add(pair.refresh)
return issue_tokens(claims['sub'])
@app.get('/me')
def me(token: str = Depends(oauth2)):
claims = jwt.decode(token, SECRET, algorithms=['HS256'])
if claims.get('typ') != 'access':
raise HTTPException(401, 'wrong token type')
return {'user': claims['sub']}How the snippet works
The working surface is the class TokenPair and the functions issue_tokens, refresh and me — everything else is wiring.
From fastapi it pulls datetime, timedelta, timezone, Depends, FastAPI — the imports name exactly which library surface the snippet touches. A HTTPException is raised inside an except block, so it is conditional on that failure being handled in the first place.
What comes back is a new object, not a reference to anything passed in.
Points of care
fastapi,pydanticandjwtmust be installed first — the snippet imports them directly.- The guard
pair.refresh in revokedshort-circuits the flow with an earlyraisewhen its condition holds.
Applying it
Entry signature: def issue_tokens(user_id: str) -> TokenPair
The surface worth importing is issue_tokens; the helpers around it are private to the snippet.
Statements that matter
return {'user': claims['sub']}
except jwt.InvalidTokenError:
raise HTTPException(401, 'invalid refresh token')
return TokenPair(
access=jwt.encode(
{'sub': user_id, 'exp': now + ACCESS_TTL, 'typ': 'access'},
SECRET, algorithm='HS256'),
refresh=jwt.encode(
{'sub': user_id, 'exp': now + REFRESH_TTL, 'typ': 'refresh',
'jti': f'{user_id}-{int(now.timestamp())}'},
SECRET, algorithm='HS256'),
)
Interactive Tools for This Topic
FAQ
- Does `issue_tokens` modify its input?
- No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
- When is the exception raised?
- Inside an `except` handler — the `HTTPException` fires only while that failure type is already being handled, not on its own trigger.
- Do I need to install anything before running this?
- Yes: `fastapi`, `pydantic` and `jwt` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.