Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python PyJWT FastAPI Authentication: Secure Token Handling

Learn how to implement JWT authentication in FastAPI with PyJWT, including token creation, validation, FastAPI dependencies, security, and common pitfalls.

~5 min readPython
#JWT#FastAPI#PyJWT#Authentication
Illustration of JWT token authentication flow in FastAPI with PyJWT, showing token generation and validation.

JWT (JSON Web Tokens) is a common way to protect FastAPI endpoints, and PyJWT provides a small library for encoding and verifying these tokens. This article walks through a complete authentication flow: creating access tokens, validating them, protecting routes with a FastAPI dependency, refreshing tokens, and handling common security pitfalls.

Setting Up the Project and Dependencies

Install the required packages. PyJWT provides token encoding and decoding, FastAPI provides the web framework, and Uvicorn serves the application. python-dotenv helps load configuration from a .env file, although you can also use environment variables directly.

bash
pip install fastapi uvicorn pyjwt python-dotenv

Create a .env file to store your secret key and token expiration settings:

env
SECRET_KEY=your-secret-key-here ACCESS_TOKEN_EXPIRE_MINUTES=30 REFRESH_TOKEN_EXPIRE_DAYS=7

Use python-dotenv to load the .env file, then read the values with os.getenv:

python
import os from dotenv import load_dotenv load_dotenv() SECRET_KEY = os.getenv('SECRET_KEY') ALGORITHM = 'HS256' ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv('ACCESS_TOKEN_EXPIRE_MINUTES', 30)) REFRESH_TOKEN_EXPIRE_DAYS = int(os.getenv('REFRESH_TOKEN_EXPIRE_DAYS', 7))

The secret key must be kept private and strong. In production, store it in a secrets manager or at least use a long random string. Never hardcode it in source code.

Creating Access Tokens with PyJWT

PyJWT's encode function takes a payload, a secret key, and an algorithm. The payload typically contains claims such as sub (the subject, usually a user identifier), exp (expiration time), and iat (issued-at time). Use timezone-aware datetime objects to avoid timezone pitfalls.

python
import jwt from datetime import datetime, timedelta, timezone def create_access_token(data: dict, expires_delta: timedelta | None = None): to_encode = data.copy() if expires_delta is not None: expire = datetime.now(timezone.utc) + expires_delta else: expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) to_encode.update({'exp': expire, 'iat': datetime.now(timezone.utc)}) return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)

This function accepts a dictionary of claims, adds expiration and issued-at timestamps, and returns a signed token. The exp claim is essential: it tells PyJWT when the token is no longer valid. Without it, the token never expires, which is a security risk.

For a refresh token, use a longer expiration and include a claim such as type set to refresh to distinguish it from an access token:

python
def create_refresh_token(data: dict): to_encode = data.copy() expire = datetime.now(timezone.utc) + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS) to_encode.update({'exp': expire, 'type': 'refresh'}) return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)

Validating Tokens and Handling Errors

Decoding a token is not enough—you must verify its signature and expiration. PyJWT's decode function does both when you pass the secret and algorithm. It raises exceptions for invalid signatures, expired tokens, or missing claims.

python
import jwt from fastapi import HTTPException from jwt import ExpiredSignatureError, InvalidTokenError def decode_token(token: str) -> dict: try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) return payload except ExpiredSignatureError: raise HTTPException(status_code=401, detail='Token expired') except InvalidTokenError: raise HTTPException(status_code=401, detail='Invalid token')

Catch ExpiredSignatureError separately from InvalidTokenError. InvalidTokenError is the base class for signature mismatch, malformed tokens, and other validation failures. Returning a generic 401 response avoids leaking why the token failed.

jwt.decode automatically checks the exp claim if it is present. If you omit exp, the token is considered valid indefinitely, which is rarely what you want.

Building a FastAPI Dependency for Protected Routes

FastAPI's dependency injection system makes it straightforward to protect routes. Use HTTPBearer from fastapi.security to extract the token from the Authorization header, then validate it in a dependency that returns the current user.

python
from fastapi import Depends from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials security = HTTPBearer() def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)) -> dict: token = credentials.credentials payload = decode_token(token) # Optionally fetch the user from a database using payload['sub'] return payload

Now protect any route by adding Depends(get_current_user) as a parameter:

python
from fastapi import FastAPI app = FastAPI() @app.get('/users/me') async def read_current_user(current_user: dict = Depends(get_current_user)): return current_user

The dependency extracts the token from the Authorization: Bearer <token> header, decodes and validates it, and returns the payload. If the token is missing, HTTPBearer returns a 403 response; if it is invalid, decode_token raises a 401 HTTPException.

Handling Token Expiration and Refresh Tokens

Access tokens are short-lived to limit the damage if they are leaked. A refresh token, with a longer lifespan, can be used to obtain new access tokens without requiring the user to log in again. Implement a /refresh endpoint that validates the refresh token and issues a new access token.

python
from pydantic import BaseModel class RefreshRequest(BaseModel): refresh_token: str @app.post('/refresh') async def refresh_token(request: RefreshRequest): payload = decode_token(request.refresh_token) if payload.get('type') != 'refresh': raise HTTPException(status_code=401, detail='Invalid token type') user_id = payload.get('sub') if not user_id: raise HTTPException(status_code=401, detail='Invalid token payload') new_access_token = create_access_token({'sub': user_id}) return {'access_token': new_access_token, 'token_type': 'bearer'}

The endpoint checks that the token is a refresh token and contains a subject, then issues a new access token. You can also rotate refresh tokens by revoking the old one and issuing a new one, but that requires server-side token state. If you need revocation, consider a token blacklist or a database-backed session store.

Security Considerations for JWT in Production

JWT security depends heavily on how you handle the secret key, algorithm, and client-side token storage.

Secret key management: Use a strong, random key. Store it in an environment variable or a secrets manager. Rotate it periodically, but note that rotating the key invalidates all existing tokens. Plan for a grace period where both old and new keys are accepted during transitions.

Algorithm selection: HS256 is symmetric; the same key signs and verifies tokens. RS256 uses a private key to sign and a public key to verify, which is useful when multiple services need to verify tokens without sharing the signing key. PyJWT supports both, but HS256 is simpler for a single-service application.

Token storage on the client: Storing tokens in localStorage makes them accessible to JavaScript, increasing the risk of XSS theft. Using httpOnly cookies mitigates this but requires CSRF protection. For API-only backends, the Authorization header is standard, but make sure your frontend uses secure storage practices.

Clock skew: The exp claim is checked against the server's current time. If the server clock differs from the client's, tokens may appear expired prematurely. PyJWT allows a small leeway via the leeway parameter in decode:

python
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM], leeway=10)

This permits up to 10 seconds of leeway when checking a token's expiration time.

Common Pitfalls and How to Avoid Them

Decoding without verification: Calling jwt.decode(token, options={'verify_signature': False}) skips signature checks. This is only for debugging and must never appear in production code.

Using naive datetime for expiration: datetime.utcnow() returns a naive datetime, which PyJWT treats as UTC. Mixing naive and aware datetimes can cause off-by-one errors. Use datetime.now(timezone.utc) consistently.

Not checking the token type: If you use both access and refresh tokens, ensure your dependencies check the type claim. Otherwise, a refresh token could be used as an access token, extending its validity beyond the intended limit.

Catching too broad exceptions: Catching Exception around jwt.decode can hide unexpected errors. Catch specific PyJWT exceptions and let others propagate.

Hardcoding the secret key: Embedding the secret in source code makes it available to anyone with repository access. Use environment variables or a secrets manager.

Ignoring token revocation: JWT is stateless, so you cannot invalidate a token before it expires without additional infrastructure. If you need immediate revocation, maintain a blacklist of revoked token IDs (the jti claim) in a database or cache.

Addressing these pitfalls makes your FastAPI authentication more robust and secure. PyJWT and FastAPI provide a solid foundation for stateless authentication, but a secure implementation depends on how you apply these patterns.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.