The idea
After login, the server issues a JSON Web Token: a small JSON payload (user ID, expiry, roles) plus a signature made with a secret key. The client sends it on every request in the Authorization: Bearer header. The server verifies the signature and expiry without a database lookup.
Keep access tokens short-lived (minutes to an hour) and use refresh tokens to get new ones. Never put secrets in the payload: it is encoded, not encrypted. Always verify the algorithm and the signature, and reject expired tokens.
For many products, a managed auth provider (Auth0, Clerk, Supabase, Firebase, Cognito) issues the JWTs and you only verify them.
Every AI feature needs to know who the user is for permissions, budgets, memory and audit logs.
Words to know
- ClaimsThe fields in a JWT payload, like sub (user) and exp (expiry).
- Bearer tokenA token that grants access to whoever holds it.
Try it without code
Decode a JWT
- Paste a sample token into jwt.io.
- Read the header and payload.
- Notice the payload is readable by anyone.
Use it in code
Issue and verify JWTs in FastAPI with PyJWT.
# pip install pyjwt
import datetime, jwt
from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
SECRET = "load-me-from-env"
app, bearer = FastAPI(), HTTPBearer()
def issue(user_id: str):
exp = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=30)
return jwt.encode({"sub": user_id, "exp": exp}, SECRET, algorithm="HS256")
def current_user(creds: HTTPAuthorizationCredentials = Depends(bearer)):
try:
return jwt.decode(creds.credentials, SECRET, algorithms=["HS256"])["sub"]
except jwt.PyJWTError:
raise HTTPException(401, "Invalid or expired token")
@app.get("/me")
def me(user: str = Depends(current_user)):
return {"user": user}Protect every endpoint of your API with current_user and pass the user ID into retrieval filters and budgets.
Common mistakes
- Long-lived access tokens.
- Accepting the algorithm from the token header.
- Storing tokens in localStorage on sensitive apps.