Building a Secure API with OAuth2 and JWT in FastAPI

In today’s API-driven applications, securing endpoints requires you to protect sensitive data and prevent unauthorized access. FastAPI, a modern web framework for Python, makes it easy to build secure, high-performance APIs using standards like OAuth2 and JWT (JSON Web Tokens).

This guide explains the core concepts of OAuth2 and JWT, why they matter, and walks you through implementing secure authentication in FastAPI step by step.

What is OAuth2?

OAuth2 is an industry-standard protocol for authorization. Users can grant limited access to their resources without sharing credentials. In API development, it’s commonly used to issue access tokens that applications can use to access protected routes.

What is JWT?

JSON Web Tokens (JWT) can be used by two parties to securely exchange claims in a compact, URL-safe format. Developers use JWT to securely transmit information and support stateless authentication in APIs.

To understand JWT better, a JWT consists of three parts:

  • Header: Specifies the algorithm used.
  • Payload: Contains the claims (e.g., user ID, roles).
  • Signature: Verifies the token hasn’t been tampered with.

Why Use OAuth2 with JWT in FastAPI?

FastAPI securely delivers scalable access control when using OAuth2 with JWT:

  • Stateless authentication (no server-side session storage).
  • Easy integration with frontend apps.
  • Scalable and secure access control.

Step-by-Step Implementation

1. Install FastAPI and Dependencies

pip install fastapi uvicorn python-jose passlib[bcrypt]

2. Basic FastAPI App Setup

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello, Secure World!"}

3. Define User and Authentication Models

from pydantic import BaseModel

class User(BaseModel):
    username: str
    disabled: bool = False

class UserInDB(User):
    hashed_password: str

class Token(BaseModel):
    access_token: str
    token_type: str

class TokenData(BaseModel):
    username: str | None = None

4. Utility Functions for JWT and Password Hashing

from datetime import datetime, timedelta
from jose import JWTError, jwt
from passlib.context import CryptContext

SECRET_KEY = "your_secret_key"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

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)

def create_access_token(data: dict, expires_delta: timedelta | None = 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})
    return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)

5. OAuth2 Password Flow with Token Endpoint

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

# Dummy DB
fake_users_db = {
    "alice": {
        "username": "alice",
        "hashed_password": get_password_hash("secret"),
        "disabled": False
    }
}

def get_user(db, username: str):
    if username in db:
        user_dict = db[username]
        return UserInDB(**user_dict)

def authenticate_user(username: str, password: str):
    user = get_user(fake_users_db, username)
    if not user or not verify_password(password, user.hashed_password):
        return False
    return user

@app.post("/token", response_model=Token)
def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token = create_access_token(data={"sub": user.username})
    return {"access_token": access_token, "token_type": "bearer"}

6. Securing Routes with JWT

from fastapi import Security

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
        token_data = TokenData(username=username)
    except JWTError:
        raise credentials_exception
    user = get_user(fake_users_db, token_data.username)
    if user is None:
        raise credentials_exception
    return user

@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
    return current_user

Conclusion

With FastAPI, implementing a secure API using OAuth2 and JWT is efficient and clean. This setup protects your endpoints, validates tokens, and securely authenticates users. As a result of following this guide, you now have a foundation for building modern, secure APIs ready for production use.

Next steps could include integrating a database, refresh tokens, and role-based access control for even more robust security.

Keep Coding…

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top