Securing Your Python Backend: JWT Authentication in FastAPI

Written by: Rizqi Mulki – Python Backend Developer

FastAPI has become one of the most popular frameworks for building fast and efficient APIs. However, security remains a top priority. In this guide, I’ll share how to implement JWT (JSON Web Token) Authentication in FastAPI to protect your API endpoints.

Why Use JWT?

JWT is an open standard (RFC 7519) that allows secure transmission of data between server and client. Key advantages:

  • Stateless – No server-side session storage
  • Scalable – Ideal for microservices architecture
  • Flexible – Can contain additional payload data

Step 1: FastAPI Project Setup

First, install required dependencies:

pip install fastapi uvicorn python-jose[cryptography] passlib[bcrypt] python-multipart

Project structure:

myapi/
├── app/
│   ├── auth.py         # JWT logic
│   ├── models.py       # Pydantic & DB models
│   ├── dependencies.py # Auth dependencies
│   └── main.py         # FastAPI app

Step 2: JWT Implementation

1. Create User & Token Models

# models.py
from pydantic import BaseModel

class User(BaseModel):
    username: str
    password: str

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

2. JWT Creation & Verification

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

SECRET_KEY = "your-secret-key-here"
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 create_access_token(data: dict):
    to_encode = data.copy()
    expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)

Step 3: Protect Endpoints with JWT

1. Create Authentication Dependency

# dependencies.py
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

async def get_current_user(token: str = Depends(oauth2_scheme)):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid credentials",
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
    except JWTError:
        raise credentials_exception
    return username

2. Use in Protected Endpoint

# main.py
from fastapi import FastAPI, Depends

app = FastAPI()

@app.post("/protected-route")
async def protected_route(current_user: str = Depends(get_current_user)):
    return {"message": f"Hello, {current_user}!"}

Step 4: Testing with Swagger UI

  • Open http://localhost:8000/docs
  • Click “Authorize” and enter your token
  • Test the /protected-route endpoint

Security Best Practices

  • Always use HTTPS to prevent MITM attacks
  • Store SECRET_KEY securely (use environment variables)
  • Implement rate limiting against brute force attacks
  • Use short token expiration (15-30 minutes)

For Recruiters

I’m an experienced Backend Developer specializing in secure API development with FastAPI and JWT. If you’re looking for a candidate who understands system security, let’s connect:

What security challenges have you faced? Share your experiences in the comments! 👇

Tags: FastAPI, JWT, Authentication, Python, Security


Comments

Leave a Reply

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

CAPTCHA ImageChange Image