11. Authentication with JWT & OAuth2
Authentication is the process of verifying who a user is. In modern APIs, JSON Web Tokens (JWT) are the standard for authentication because they are stateless, scalable, and secure. FastAPI provides built-in tools for implementing OAuth2 with JWT. To test these examples, save to main.py and run uvicorn main:app --reload.
What is JWT?
JWT (JSON Web Token) is a compact, URL-safe token format that contains claims about the user. A JWT consists of three parts: Header (algorithm), Payload (user data), and Signature (verification). The token is signed by the server, so the client cannot modify it without invalidating the signature.
import jwt from datetime import datetime, timedelta SECRET_KEY = "your-secret-key" ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 30 def create_access_token(data: dict, expires_delta: timedelta = None): to_encode = data.copy() if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt def decode_token(token: str): try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) return payload except jwt.ExpiredSignatureError: return None except jwt.InvalidTokenError: return None token = create_access_token({"sub": "user123"}) print(f"Token: {token}") print(f"Decoded: {decode_token(token)}")
OAuth2 Password Flow Setup
FastAPI includes OAuth2PasswordBearer for handling token authentication. This creates an endpoint that expects username and password and returns a token.
from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from pydantic import BaseModel from datetime import datetime, timedelta import jwt app = FastAPI() SECRET_KEY = "your-secret-key" ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 30 oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") class Token(BaseModel): access_token: str token_type: str class User(BaseModel): username: str email: str = None disabled: bool = False # Fake database fake_users_db = { "alice": { "username": "alice", "email": "alice@example.com", "hashed_password": "fakehashedsecret", "disabled": False, } } def verify_password(plain_password, hashed_password): return plain_password == hashed_password def get_user(db, username: str): if username in db: return User(**db[username]) return None def authenticate_user(fake_db, username: str, password: str): user = get_user(fake_db, username) if not user: return False if not verify_password(password, fake_db[username]["hashed_password"]): return False return user @app.post("/token", response_model=Token) async def login(form_data: OAuth2PasswordRequestForm = Depends()): user = authenticate_user(fake_users_db, 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_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) return {"access_token": access_token, "token_type": "bearer"} @app.get("/users/me") async def read_users_me(token: str = Depends(oauth2_scheme)): return {"token": token}
Password Hashing with Passlib
Never store plain text passwords. Use bcrypt to hash passwords before storing them.
from passlib.context import CryptContext pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") def verify_password(plain_password, hashed_password): return pwd_context.verify(plain_password, hashed_password) def get_password_hash(password): return pwd_context.hash(password) # Hash a password hashed = get_password_hash("secretpassword") print(f"Hashed: {hashed}") # Verify password is_correct = verify_password("secretpassword", hashed) print(f"Correct: {is_correct}") is_wrong = verify_password("wrongpassword", hashed) print(f"Wrong: {is_wrong}")
pip install passlib[bcrypt]. Never store plain passwords in your database.Protected Routes with Dependency
Use the get_current_user dependency to protect routes. Only authenticated users can access these endpoints.
async def get_current_user(token: str = Depends(oauth2_scheme)): credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) username: str = payload.get("sub") if username is None: raise credentials_exception except jwt.InvalidTokenError: raise credentials_exception user = get_user(fake_users_db, username) if user is None: raise credentials_exception return user @app.get("/api/protected") async def protected_route(current_user: User = Depends(get_current_user)): return {"message": f"Hello {current_user.username}, you are authenticated!"} @app.get("/api/admin") async def admin_route(current_user: User = Depends(get_current_user)): if current_user.username != "admin": raise HTTPException(status_code=403, detail="Admin access required") return {"message": "Welcome admin!"}
Refresh Tokens
Access tokens are short-lived (15-30 minutes). Refresh tokens are long-lived (7-30 days) and can be used to obtain new access tokens without re-authenticating.
REFRESH_TOKEN_EXPIRE_DAYS = 7 def create_refresh_token(data: dict): to_encode = data.copy() expire = datetime.utcnow() + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS) to_encode.update({"exp": expire, "type": "refresh"}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @app.post("/refresh") async def refresh_access_token(refresh_token: str): try: payload = jwt.decode(refresh_token, SECRET_KEY, algorithms=[ALGORITHM]) if payload.get("type") != "refresh": raise HTTPException(status_code=401, detail="Invalid token type") username = payload.get("sub") new_access_token = create_access_token(data={"sub": username}) return {"access_token": new_access_token, "token_type": "bearer"} except jwt.ExpiredSignatureError: raise HTTPException(status_code=401, detail="Refresh token expired") except jwt.InvalidTokenError: raise HTTPException(status_code=401, detail="Invalid refresh token")
Knowledge Check
Ready to test your understanding of 11. Authentication with JWT & OAuth2?