- Courses
- 📚Libraries & Frameworks
- ⚡FastAPI
- Authentication, Authorization and Security
- OAuth2 & JWT
- JWT Authentication
On this page
JWT Authentication in FastAPI
Published on August 13, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Every request to a protected API endpoint needs to answer one question: who is making this request, and can the server trust that? A traditional approach answers it by checking a session ID against a shared store on every single request — workable at small scale, but a genuine bottleneck once an API runs across multiple servers, since every one of those servers needs access to the same session data. JSON Web Tokens solve this differently: proof of identity travels inside the request itself, as a signed, self-contained token the server can verify mathematically, with nothing about that user stored on the backend at all. This covers what a JWT actually contains, how to issue one at login, and how to require one on every protected route — the pattern behind nearly all modern stateless APIs.
Session-Based vs. Token-Based Authentication​
The scalability problem with server-side sessions​
In a session-based system, logging in makes the server generate a unique session ID, store it in memory or a database, and hand it to the client as a cookie. Every subsequent request from that client carries the cookie, and the server checks it against that same store before deciding whether to proceed. This works cleanly on a single server, but scaling horizontally — running the same API across several servers or regions — means every one of those servers needs to see the same session data, which typically means introducing a shared, synchronized session store as a new piece of infrastructure to run and keep available.
How stateless token authentication solves it​
A JWT moves that proof of identity out of server-side storage entirely. At login, the server packages the authenticated user's identity into a token, signs it with a secret only the server knows, and hands the token to the client. On every later request, the client sends that same token back, and the server checks its signature mathematically — no database lookup, no shared store, nothing to keep in sync across multiple servers. Any server holding the same signing secret can verify a token issued by any other server in the same system, which is what makes this approach scale horizontally without extra coordination.
What a JWT Actually Contains​
A JWT is a compact, URL-safe string made of three parts separated by dots: header.payload.signature.
The header carries metadata about the token itself — which signing algorithm was used, most commonly HS256. The payload carries the actual claims: data about the authenticated user, typically including a sub (subject) claim identifying who the token belongs to, and an exp (expiration) claim stating when the token stops being valid. The signature is generated by combining the encoded header and payload with a secret key known only to the server, and it's what makes the token tamper-evident — changing anything in the header or payload without knowing that secret produces a signature that no longer matches, and the server rejects the token outright.
One detail matters enormously here and is easy to miss: the header and payload are base64-encoded, not encrypted. Anyone holding a JWT can decode its contents instantly using nothing more than a text editor — the signature proves the contents haven't been altered, but it does nothing to hide them. Nothing sensitive — a password, a full set of personal data — belongs inside a JWT payload.
Installing the Right Libraries​
python-jose, still referenced in a lot of older FastAPI material for JWT handling, has had no release since 2021 and is no longer actively maintained. FastAPI's own current documentation has moved to PyJWT in its place, which is actively maintained and has a simpler, more focused API. The same shift applies to password hashing: passlib is unmaintained and breaks on Python 3.13 and later, and current FastAPI documentation uses pwdlib instead.
pip install pyjwt "pwdlib[argon2]" python-multipart
python-multipart is required separately: FastAPI's OAuth2 login flow expects credentials as form data rather than JSON, and parsing that format depends on this package being installed.
Configuration and Core Security Helpers​
core/security.py:
import os
from datetime import datetime, timedelta, timezone
import jwt
from jwt.exceptions import InvalidTokenError
from pwdlib import PasswordHash
SECRET_KEY = os.environ["SECRET_KEY"] # loaded from the environment — never hardcoded
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
password_hash = PasswordHash.recommended()
def get_password_hash(password: str) -> str:
"""Converts a plaintext password into a salted Argon2 hash."""
return password_hash.hash(password)
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""Checks a login attempt's password against the stored hash."""
return password_hash.verify(plain_password, hashed_password)
def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
"""Generates a signed JWT containing the given data, with an expiration claim."""
to_encode = data.copy()
expire = datetime.now(timezone.utc) + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
to_encode.update({"exp": expire})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
def decode_access_token(token: str) -> dict | None:
"""Verifies a token's signature and expiration, returning its claims if valid."""
try:
return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
except InvalidTokenError:
return None
SECRET_KEY = os.environ["SECRET_KEY"] reads the signing key from an environment variable and raises immediately if it's missing, rather than silently falling back to a hardcoded value — a JWT's entire security rests on this key staying private, and a value checked into source code is a value that's already leaked the moment the repository is shared or made public. create_access_token sets exp using datetime.now(timezone.utc), producing a timezone-aware timestamp rather than a naive one — this matters because jwt.encode compares expiration against the current UTC time internally, and a naive timestamp risks being interpreted against the wrong timezone depending on the environment it runs in. decode_access_token catches InvalidTokenError, which covers both an invalid signature and an expired token — either failure returns None rather than raising, leaving the caller to decide how to respond.
Issuing a Token at Login​
routers/auth.py:
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from core.security import create_access_token, verify_password, get_password_hash
router = APIRouter(prefix="/auth", tags=["Authentication"])
FAKE_USER_DB = {
"johndoe": {
"username": "johndoe",
"hashed_password": get_password_hash("secret123"),
"email": "[email protected]",
}
}
@router.post("/login")
def login(form_data: OAuth2PasswordRequestForm = Depends()):
user = FAKE_USER_DB.get(form_data.username)
if not user or not verify_password(form_data.password, user["hashed_password"]):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token = create_access_token(data={"sub": user["username"]})
return {"access_token": access_token, "token_type": "bearer"}
OAuth2PasswordRequestForm parses the incoming form data into form_data.username and form_data.password, matching the field names the OAuth2 specification requires. data={"sub": user["username"]} is what ends up encoded as the token's payload — sub is the conventional claim name for "the identity this token belongs to." The WWW-Authenticate: Bearer header on the 401 response isn't decorative; it's part of the HTTP specification for authentication failures using the Bearer scheme.
Protecting Routes with a Dependency​
core/dependencies.py:
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from core.security import decode_access_token
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")
def get_current_user(token: str = Depends(oauth2_scheme)) -> str:
payload = decode_access_token(token)
if payload is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
username = payload.get("sub")
if username is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token claims",
headers={"WWW-Authenticate": "Bearer"},
)
return username
OAuth2PasswordBearer(tokenUrl="/auth/login") tells FastAPI two things at once: to look for an Authorization: Bearer <token> header on incoming requests, and to point Swagger UI's login form at /auth/login so the interactive docs know where to fetch a token from. get_current_user decodes the token and checks two things independently — that the signature and expiration are valid at all, and that the resulting payload actually contains a sub claim — since a token could in principle be validly signed but missing the specific claim this application depends on.
Applying this to a route requires nothing more than declaring the dependency:
from fastapi import APIRouter, Depends
from core.dependencies import get_current_user
router = APIRouter(prefix="/tasks", tags=["Tasks"])
@router.get("/", response_model=dict)
def read_user_tasks(current_user: str = Depends(get_current_user)):
return {
"user": current_user,
"tasks": [
{"task_id": 1, "title": "Configure production environment variables", "done": False},
{"task_id": 2, "title": "Implement user registration", "done": True},
],
}
Depends(get_current_user) runs before read_user_tasks itself — if the token is missing, expired, or invalid, the 401 is raised inside the dependency and the route's own body never executes.
Testing the Full Flow in Swagger UI​
Setting SECRET_KEY as an environment variable and starting the server, then opening http://127.0.0.1:8000/docs, allows testing the entire flow without any external tool. Expanding POST /auth/login, clicking "Try it out," and submitting johndoe / secret123 returns a JSON body containing access_token. Copying that token into the green "Authorize" button at the top of the page — the lock icon — applies it to every subsequent request made from within Swagger UI automatically. Expanding GET /tasks/ and executing it afterward shows the request succeeding, with Swagger UI attaching the Authorization: Bearer <token> header behind the scenes.
Architecture Recap​
ComponentRoleAccess tokenProves identity statelessly, with no server-side lookup requiredcreate_access_token()Signs a token and attaches an expiration claimdecode_access_token()Verifies the signature and extracts the claimsget_current_user()Reads the token from the request and enforces it as a dependency on protected routes
Security Considerations​
A JWT's payload is readable by anyone holding the token, since it's encoded rather than encrypted — nothing sensitive belongs inside it, and keeping the payload small keeps every request carrying it lighter. Because a JWT is verified purely through its signature and expiration, revoking one before it naturally expires isn't automatic — a compromised or logged-out token stays technically valid until exp passes unless the application tracks revoked tokens separately, commonly through a fast lookup store like Redis checked on every request. HS256, used throughout this article, relies on a single shared secret known to every service that needs to sign or verify a token — fine for a single application, but a liability across multiple independent services, since any one of them holding the secret can forge tokens for all the others. RS256, an asymmetric alternative using a private/public key pair, lets a token be signed with a private key only one service holds, while every other service verifies it using a public key that carries no signing power of its own.
Key Takeaways​
A JWT replaces server-side session storage with a self-contained, signed token — header.payload.signature — that any server holding the shared secret can verify independently, which is what makes stateless authentication scale horizontally without a synchronized session store. PyJWT and pwdlib are the current, actively maintained libraries behind this pattern in FastAPI, having replaced python-jose and passlib, both of which are unmaintained. OAuth2PasswordBearer combined with a get_current_user dependency is the standard shape for protecting a route — reading the token, verifying it, and short-circuiting with a 401 before the route's own logic runs. And because a JWT's payload is only encoded, never encrypted, and its validity can't be revoked early without extra infrastructure, what goes inside the payload and how token revocation is handled are both decisions worth making deliberately rather than by default.
Practice: Registration, Profile, and Revocation​
routers/auth.py (continued):
from pydantic import BaseModel, EmailStr, Field
class UserRegisterSchema(BaseModel):
username: str
email: EmailStr
password: str = Field(..., min_length=8)
@router.post("/register", status_code=201)
def register(user_data: UserRegisterSchema):
if user_data.username in FAKE_USER_DB:
raise HTTPException(status_code=400, detail="Username already exists")
FAKE_USER_DB[user_data.username] = {
"username": user_data.username,
"hashed_password": get_password_hash(user_data.password),
"email": user_data.email,
}
return {"message": "User registered successfully", "username": user_data.username}
This follows the same shape as login: check for a collision before writing, hash the password through the same get_password_hash helper already defined, and never store the plaintext value anywhere.
A profile endpoint built on the existing get_current_user dependency:
@router.get("/users/me")
def read_profile(current_user: str = Depends(get_current_user)):
user = FAKE_USER_DB.get(current_user)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return {"username": user["username"], "email": user["email"]}
current_user is already the verified username by the time this function runs — get_current_user extracted it from the token's sub claim and validated the token's signature and expiration before this route's body ever executes.
A minimal revocation mechanism, tracking logged-out tokens in memory:
REVOKED_TOKENS: set[str] = set()
@router.post("/logout")
def logout(token: str = Depends(oauth2_scheme)):
REVOKED_TOKENS.add(token)
return {"message": "Logged out successfully"}
def get_current_user(token: str = Depends(oauth2_scheme)) -> str:
if token in REVOKED_TOKENS:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token has been revoked",
headers={"WWW-Authenticate": "Bearer"},
)
payload = decode_access_token(token)
if payload is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
return payload.get("sub")
Checking REVOKED_TOKENS before decoding means a logged-out token is rejected immediately, without needing to wait for its natural expiration. REVOKED_TOKENS as a plain in-memory set carries the same limitation any single-process, in-memory store does: it resets to empty on every server restart, and it isn't shared across multiple server processes or machines — a token revoked on one server instance would still be accepted by another. A shared store like Redis, checked by every server instance alike, is what removes that limitation in a real deployment.
Frequently Asked Questions​
Why does the app crash on startup with a KeyError for SECRET_KEY?
This means the SECRET_KEY environment variable hasn't been set before starting the server. Since the code reads it with os.environ["SECRET_KEY"] rather than a hardcoded default, the app fails loudly and immediately if it's missing, instead of silently running with no signing key. Set the variable in the shell or in a .env file loaded before the app starts.
Why does /auth/login return a 422 error instead of checking my credentials?
OAuth2PasswordRequestForm expects the request body as application/x-www-form-urlencoded data with fields named exactly username and password — not JSON. Sending a JSON body to this endpoint fails validation before the login logic ever runs. Testing through Swagger UI's built-in form, or sending form-encoded data directly, avoids this.
Why do I get an error mentioning python-multipart when I call /auth/login?
OAuth2PasswordRequestForm depends on the python-multipart package to parse form-encoded request bodies. If it isn't installed, FastAPI raises an explicit error stating that form parsing requires it. Installing it with pip install python-multipart resolves this.
I have a valid token, but get_current_user still returns a 401. Why?
Two independent checks happen inside get_current_user, and either one can fail: the token's signature and expiration might be invalid (checked first), or the payload might be valid but missing the sub claim entirely (checked second). Confirm the token wasn't generated without a sub key in the data passed to create_access_token, and check that it hasn't expired based on the exp claim.
Why does decode_access_token return None instead of raising an exception on a bad token?
This is intentional — decode_access_token catches InvalidTokenError internally and returns None for any failure, whether that's an invalid signature or an expired token. This keeps the calling code (get_current_user) simple: it only needs to check for None rather than catching multiple different exception types itself.
Can I read the contents of a JWT without the secret key?
Yes — the header and payload are base64-encoded, not encrypted, so anyone holding the token string can decode and read its claims instantly with no secret required. Only the signature requires the secret key, and only for verifying that the contents haven't been tampered with. This is exactly why no sensitive data — passwords, personal information — should ever go inside a JWT payload.
I revoked a token with /logout, but it still works on a different server instance. Why?
The REVOKED_TOKENS set used in this article lives in a single process's memory, so it isn't shared across multiple server instances or restarts. A token revoked on one instance is still considered valid by another instance that never saw the revocation. A shared store like Redis, checked by every instance, is what's needed for revocation to work correctly across more than one server.
Why does a revoked or logged-out token still get accepted after a server restart?
Because REVOKED_TOKENS is a plain in-memory set, restarting the server clears it completely along with everything else in memory. Any token revoked before the restart is treated as valid again afterward. Persisting revoked tokens somewhere outside the process — a database or Redis — is required for revocation to survive a restart.
Should I use HS256 or RS256 for signing tokens?
HS256 uses one shared secret for both signing and verifying, which is simple and sufficient for a single application. RS256 uses a private/public key pair instead — only the key that issues tokens needs the private key, while every other service can verify tokens using only the public key. RS256 is worth the added complexity specifically when multiple independent services need to verify tokens without all of them being trusted to sign new ones.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Password Hashing
Next
Role-Based Access Control (RBAC)
-
Session-Based vs. Token-Based Authentication
- The scalability problem with server-side sessions
- How stateless token authentication solves it
-
What a JWT Actually Contains
-
Installing the Right Libraries
-
Configuration and Core Security Helpers
-
Issuing a Token at Login
-
Protecting Routes with a Dependency
-
Testing the Full Flow in Swagger UI
-
Architecture Recap
-
Security Considerations
-
Key Takeaways
-
Practice: Registration, Profile, and Revocation
-
Frequently Asked Questions
