How to Implement JWT Authentication in FastAPI
Implement JWT auth in FastAPI with PyJWT, Argon2 hashing, scoped dependencies, refresh-token rotation, and tests for expired and invalid tokens.
On this page
Introduction
JSON Web Tokens are a compact way to carry signed claims between a client and an API. In a FastAPI service they are often used for stateless authentication: the server signs a token at login, the client sends it with each request, and the server verifies the signature and claims without a session lookup. That model scales well, but it is easy to implement in a way that trusts the wrong data or cannot revoke a compromised credential.
This tutorial builds a complete flow: environment-backed signing keys, Argon2 password hashing, short-lived access tokens, explicit claim verification, a FastAPI dependency that returns the current user, and refresh-token rotation backed by a database. It also covers the failure cases that matter: expired tokens, wrong signatures, algorithm confusion, and token reuse. The examples target FastAPI with PyJWT 2.x.
Configure secrets and password hashing
Never hard-code a signing secret. Generate one with a cryptographically secure source and load it from the environment:
python -c "import secrets; print(secrets.token_urlsafe(48))"
import os
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
jwt_secret: str
jwt_issuer: str = "example-api"
jwt_audience: str = "example-web"
access_ttl_seconds: int = 900
refresh_ttl_seconds: int = 60 * 60 * 24 * 30
settings = Settings()
Pydantic Settings raises at startup when JWT_SECRET is missing. That is preferable to falling back to an empty string that silently signs tokens anyone can forge. In production, inject the secret through the platform’s secret manager rather than a committed .env file.
Hash passwords with Argon2 instead of SHA-256 or a fast hash. pwdlib provides a modern wrapper:
pip install "pwdlib[argon2]" pyjwt fastapi
from pwdlib import PasswordHash
password_hash = PasswordHash.recommended()
hashed = password_hash.hash("correct horse battery staple")
is_valid = password_hash.verify("correct horse battery staple", hashed)
Argon2 is deliberately slow and memory-hard, which raises the cost of offline cracking. Store only the hash. At login, compare with the library’s verify function, never with ==, so the comparison remains constant-time.
Issue access tokens with explicit claims
A token should contain the minimum identity needed by the API, plus claims that make verification meaningful:
from datetime import datetime, timedelta, timezone
from uuid import uuid4
import jwt
def create_access_token(user_id: str, roles: list[str]) -> str:
now = datetime.now(timezone.utc)
payload = {
"sub": user_id,
"roles": roles,
"iat": now,
"nbf": now,
"exp": now + timedelta(seconds=settings.access_ttl_seconds),
"iss": settings.jwt_issuer,
"aud": settings.jwt_audience,
"jti": uuid4().hex,
}
return jwt.encode(payload, settings.jwt_secret, algorithm="HS256")
sub must be a string; some libraries and gateways reject numeric subjects. jti gives the token an identity, which is useful for logging and for a denylist when immediate revocation is required. Do not put passwords, email addresses, or other sensitive personal data in the payload; JWT payloads are signed, not encrypted, and anyone holding the token can read them.
exp, nbf, and iat are Unix timestamps. PyJWT validates exp and nbf automatically when decoding. Include a small clock skew allowance if the issuer and verifier run on different hosts:
jwt.decode(..., options={"leeway": 30})
Verify tokens with an explicit algorithm
Verification must pin the algorithm and validate the issuer and audience. A decoder that accepts the algorithm named in the token header is vulnerable to algorithm confusion:
from jwt import InvalidTokenError
def decode_access_token(token: str) -> dict:
try:
return jwt.decode(
token,
settings.jwt_secret,
algorithms=["HS256"],
audience=settings.jwt_audience,
issuer=settings.jwt_issuer,
options={"require": ["exp", "sub", "iss", "aud"]},
)
except InvalidTokenError as exc:
raise ValueError("invalid token") from exc
Requiring claims prevents a token without an expiry from being accepted indefinitely. Pinning algorithms prevents a token signed with none or with a different algorithm from being treated as valid. Catch InvalidTokenError at the boundary and convert it to an HTTP response; do not leak the decoder’s exception text to clients.
If several services verify tokens without sharing the signing key, switch to asymmetric signing. The issuer holds the private key and signs with RS256 or EdDSA; verifiers hold only the public key. Key rotation then becomes a matter of publishing a new key id and keeping the old public key available until existing tokens expire. Put the key id in the token header (kid) so verifiers can select the right key.
Protect routes with a dependency
FastAPI dependencies make authentication reusable and testable. HTTPBearer extracts the Authorization: Bearer header; auto_error=False lets the dependency return a consistent 401 instead of a framework-specific error:
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
app = FastAPI()
bearer = HTTPBearer(auto_error=False)
async def get_current_user(
credentials: HTTPAuthorizationCredentials | None = Depends(bearer),
) -> dict:
if credentials is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = decode_access_token(credentials.credentials)
except ValueError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired token",
headers={"WWW-Authenticate": "Bearer"},
)
user = await load_user(payload["sub"])
if user is None or not user.is_active:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Inactive user")
return {"id": user.id, "roles": payload.get("roles", [])}
@app.get("/profile")
async def profile(user: dict = Depends(get_current_user)) -> dict:
return {"id": user["id"], "roles": user["roles"]}
Return the same generic message for “unknown user” and “wrong password” at login, and use a dummy hash verification when the user does not exist. Otherwise response timing and error text reveal which accounts are valid.
Authorization is separate from authentication. A valid token proves who the caller is, not what they may do. Check ownership or roles inside each handler or in a second dependency:
def require_role(role: str):
async def dependency(user: dict = Depends(get_current_user)) -> dict:
if role not in user["roles"]:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
return user
return dependency
Do not put authorization decisions in the token alone. Roles can change after a token is issued; if immediate role changes matter, keep token lifetimes short or look up current permissions on each request.
Add refresh tokens with rotation
A long-lived access token is convenient and dangerous. Use a short access token plus a refresh token that is stored server-side, hashed, and rotated on every use. A minimal table needs the token hash, user id, family id, expiry, and revocation state.
import hashlib
from datetime import datetime, timezone
from uuid import uuid4
def hash_refresh_token(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
async def issue_refresh_token(user_id: str, family_id: str | None = None) -> str:
raw = uuid4().hex + uuid4().hex
await refresh_store.insert(
token_hash=hash_refresh_token(raw),
user_id=user_id,
family_id=family_id or uuid4().hex,
expires_at=datetime.now(timezone.utc) + timedelta(seconds=settings.refresh_ttl_seconds),
revoked=False,
)
return raw
On refresh, look up the hash. If it is missing, expired, or revoked, reject the request. If a token that was already rotated is presented again, treat it as reuse: revoke the entire token family and force a new login. This is the standard defense against a stolen refresh token being replayed after rotation.
Refresh tokens belong in an HttpOnly, Secure, SameSite cookie for browser clients, with CSRF protection on the refresh endpoint. Native or server-to-server clients can keep them in secure storage and send them in a request body. Never put a refresh token in a URL or a log line.
Test the failure paths
Tests should cover more than a valid login. Use a temporary secret and fixed clock values:
from fastapi.testclient import TestClient
client = TestClient(app)
def test_profile_requires_token():
response = client.get("/profile")
assert response.status_code == 401
assert response.headers["www-authenticate"] == "Bearer"
def test_expired_token_is_rejected():
token = jwt.encode(
{
"sub": "user-1",
"exp": datetime.now(timezone.utc) - timedelta(seconds=1),
"iss": settings.jwt_issuer,
"aud": settings.jwt_audience,
},
settings.jwt_secret,
algorithm="HS256",
)
response = client.get("/profile", headers={"Authorization": f"Bearer {token}"})
assert response.status_code == 401
Also test a token signed with a different secret, a token with the wrong audience, a token with alg: none, and a refresh token reused after rotation. Assert the status code and the WWW-Authenticate header, not the exact human-readable error text.
Common pitfalls
- Hard-coded secrets. A committed secret must be treated as compromised and rotated.
- Accepting the token’s algorithm. Pass an explicit allowlist to
jwt.decode. - Skipping
exp. A token without an expiry lives until the secret changes. - Trusting roles forever. Shorten token lifetimes or re-check permissions for sensitive operations.
- Storing tokens in localStorage. XSS turns into session theft; use HttpOnly cookies for browsers.
- No refresh rotation. A stolen refresh token remains valid until expiry.
- Leaking user existence. Use generic login errors and constant-time hash verification.
Conclusion
JWT authentication in FastAPI is a small amount of signing code surrounded by a larger set of security decisions. Keep the signing key out of source control, hash passwords with Argon2, pin the verification algorithm, validate issuer and audience, keep access tokens short, rotate refresh tokens, and treat authorization as a per-request decision. The dependency system makes the happy path concise, but the failure paths are what determine whether the implementation is safe.
Sources: PyJWT documentation, FastAPI security tutorial, OWASP JSON Web Token Cheat Sheet.
FAQ
- Should JWTs be stored in localStorage?
- Avoid localStorage for browser sessions. Any script running in the page can read it, so an XSS bug becomes token theft. Prefer an HttpOnly, Secure, SameSite cookie and add CSRF protection for state-changing requests.
- How long should an access token live?
- Keep access tokens short, commonly 5 to 15 minutes, and use a refresh token to obtain a new one. A short lifetime limits the damage of a leaked token but does not replace revocation or server-side session control.
- Is HS256 secure?
- HS256 is secure when the shared secret is long, random, kept out of source control, and used by a single service. If multiple services must verify tokens without sharing a signing secret, use asymmetric signing such as RS256 or EdDSA and publish the public key.
Interactive Tools for This Topic
Report a problem with this articleOpens a pre-filled issue on GitHub.