Implementing JWT Authentication in FastAPI: A Complete Developer's Guide
JWT (JSON Web Token) is a compact token for transmitting claims between parties. The token consists of three Base64-encoded parts: header, payload, and signature, separated by periods.
Header contains the signing algorithm (e.g., HS256) and token type (JWT):
{"alg": "HS256", "typ": "JWT"}
Payload stores claims: sub (user identifier), iat (issued at time), exp (expiration time):
{"sub": "alex", "name": "Alex Tomchok", "iat": 1516239022, "exp": 1516242622}
Signature is computed as HMAC-SHA256 of (header.payload + secret_key). The server verifies the signature during validation: any change to the payload invalidates the token. Data is readable but protected from modification.
Access tokens have a short lifespan (15β30 minutes), while refresh tokens are long-lived (days/months). This example uses only access tokens.
Project Setup and Dependencies
Create the structure:
fastapi-jwt-auth/
βββ app/
β βββ main.py
β βββ core/
β β βββ config.py
β β βββ security.py
β βββ schemas/
β β βββ token.py
β β βββ user.py
β βββ api/
β β βββ v1/
β β βββ endpoints/
β β β βββ auth.py
β β β βββ users.py
β β βββ dependencies.py
β βββ services/
β βββ user_service.py
βββ requirements.txt
requirements.txt:
fastapi==0.104.1
uvicorn[standard]==0.24.0
python-jose[cryptography]==3.3.0
passlib[bcrypt]==1.7.4
python-multipart==0.0.6
pydantic[email]==2.5.0
Install: pip install -r requirements.txt.
Configuration and Pydantic Schemas
In core/config.py, define settings using Pydantic:
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
SECRET_KEY: str = "your-super-secret-key-change-this-in-production"
ALGORITHM: str = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
class Config:
env_file = ".env"
settings = Settings()
Schemas in schemas/user.py:
from pydantic import BaseModel, EmailStr
class UserBase(BaseModel):
username: str
email: EmailStr
class UserCreate(UserBase):
password: str
class User(UserBase):
id: int
is_active: bool = True
class Config:
from_attributes = True
class UserInDB(User):
hashed_password: str
schemas/token.py:
from pydantic import BaseModel
class Token(BaseModel):
access_token: str
token_type: str = "bearer"
class TokenData(BaseModel):
username: str | None = None
Security: Hashing and JWT Operations
In core/security.py, implement password hashing (bcrypt) and JWT functions:
from datetime import datetime, timedelta
from jose import JWTError, jwt
from passlib.context import CryptContext
from .config import settings
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
def create_access_token(data: dict) -> str:
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return encoded_jwt
def decode_access_token(token: str) -> dict:
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
return payload
except JWTError:
return None
User Service and Fake Database
services/user_service.py with in-memory storage:
from app.schemas.user import UserInDB
from app.core.security import verify_password, get_password_hash
fake_users_db = {
"alex": {
"id": 1,
"username": "alex",
"email": "[email protected]",
"hashed_password": get_password_hash("secret123"),
"is_active": True,
}
}
def get_user_by_username(username: str) -> UserInDB | None:
if username in fake_users_db:
return UserInDB(**fake_users_db[username])
return None
def authenticate_user(username: str, password: str) -> UserInDB | None:
user = get_user_by_username(username)
if not user:
return None
if not verify_password(password, user.hashed_password):
return None
return user
Dependencies for Authorization
In api/v1/dependencies.py, use OAuth2PasswordBearer:
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from app.core.security import decode_access_token
from app.services.user_service import get_user_by_username
from app.schemas.token import TokenData
from app.schemas.user import User
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")
async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
payload = decode_access_token(token)
if payload is None:
raise credentials_exception
username: str = payload.get("sub")
if username is None:
raise credentials_exception
user = get_user_by_username(username)
if user is None:
raise credentials_exception
return user
async def get_current_active_user(current_user: User = Depends(get_current_user)) -> User:
if not current_user.is_active:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Inactive user")
return current_user
Endpoints: Login and Protected Routes
api/v1/endpoints/auth.py:
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from app.schemas.token import Token
from app.services.user_service import authenticate_user
from app.core.security import create_access_token
router = APIRouter(prefix="/auth", tags=["authentication"])
@router.post("/login", response_model=Token)
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(form_data.username, form_data.password)
if not user:
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 Token(access_token=access_token, token_type="bearer")
api/v1/endpoints/users.py:
from fastapi import APIRouter, Depends
from app.schemas.user import User
from app.api.v1.dependencies import get_current_active_user
router = APIRouter(prefix="/users", tags=["users"])
@router.get("/me", response_model=User)
async def read_users_me(current_user: User = Depends(get_current_active_user)):
return current_user
Connect routers in main.py and run uvicorn app.main:app.
Key Points
- JWT payload is not encrypted, only signed β use only non-sensitive data.
- Store SECRET_KEY in environment variables, generate it with 32+ characters.
- In production, add refresh tokens and a database (SQLAlchemy + Alembic).
- FastAPI dependencies allow reusing authorization logic without duplication.
- Test endpoints via Swagger UI:
/docs.
β Editorial Team
No comments yet.