Python & FastAPI13 min read·By Liyabona Saki·

JWT Authentication in FastAPI — Secure APIs Properly

Implement JWT authentication in FastAPI the right way — OAuth2PasswordBearer, password hashing, access + refresh tokens and role-based access control.

Advertisement

Introduction

Authentication is the part developers most often get wrong. This tutorial builds JWT auth in FastAPI the way a security review would actually approve: hashed passwords, short-lived access tokens, refresh tokens, and clean role-based access control.

For the Java version, see Spring Boot Security with JWT.

Key takeaways

  • Hash passwords with bcrypt or argon2. Never with SHA-256.
  • Access tokens should be short-lived (5–15 min). Use refresh tokens for the rest.
  • Sign with HS256 for monoliths, RS256 for multi-service / public verification.
  • RBAC belongs in a dependency, not scattered in handlers.
  • Always validate exp, iss and aud claims.

Setup

bash
pip install "passlib[bcrypt]" "python-jose[cryptography]" "pydantic[email]"

Password hashing

```python
from passlib.context import CryptContext
pwd = CryptContext(schemes=["bcrypt"], deprecated="auto")

def hash_password(p: str) -> str: return pwd.hash(p) def verify_password(p: str, h: str) -> bool: return pwd.verify(p, h) ```

Token issuance

```python
from datetime import datetime, timedelta, timezone
from jose import jwt

SECRET, ALG, ISS = settings.JWT_SECRET, "HS256", "masterlab"

def create_token(sub: str, roles: list[str], minutes: int) -> str: now = datetime.now(timezone.utc) return jwt.encode( {"sub": sub, "roles": roles, "iss": ISS, "iat": now, "exp": now + timedelta(minutes=minutes)}, SECRET, algorithm=ALG, ) ```

Login + refresh

```python
from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm

router = APIRouter()

@router.post("/login") async def login(form: OAuth2PasswordRequestForm = Depends(), svc: UserService = Depends(get_user_service)): user = await svc.authenticate(form.username, form.password) if not user: raise HTTPException(401, "Invalid credentials") return { "access_token": create_token(str(user.id), user.roles, 15), "refresh_token": create_token(str(user.id), user.roles, 60 * 24 * 7), "token_type": "bearer", } ```

Current-user dependency

```python
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError

oauth2 = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")

async def current_user(token: str = Depends(oauth2)) -> dict: try: payload = jwt.decode(token, SECRET, algorithms=[ALG], issuer=ISS) except JWTError: raise HTTPException(401, "Invalid token") return payload

def require_roles(*roles: str): async def checker(user: dict = Depends(current_user)) -> dict: if not set(roles).intersection(user.get("roles", [])): raise HTTPException(403, "Insufficient role") return user return checker ```

Protecting endpoints

```python
@router.get("/me")
async def me(user: dict = Depends(current_user)):
    return {"id": user["sub"], "roles": user["roles"]}

@router.delete("/admin/users/{id}", dependencies=[Depends(require_roles("admin"))]) async def delete_user(id: int): ... ```

Production best practices

  • Store refresh tokens in httpOnly, Secure, SameSite=Strict cookies — not localStorage.
  • Maintain a token revocation list in Redis for logout / compromised tokens.
  • Rotate JWT secrets; support kid in the header for graceful rotation.
  • Rate-limit /login aggressively to slow credential stuffing.

Common mistakes

  • Long-lived access tokens (days) — there is no logout if you can't revoke them.
  • Signing tokens with the framework's default secret (changeme).
  • Sending the JWT in URL query strings — it lands in logs.

Tools used in this tutorial

The setup below uses the following tools. Versions matter less than the role each one plays, so swap freely as long as you keep the responsibilities the same.

  • Python 3.12+
  • FastAPI
  • Uvicorn / Gunicorn
  • Pydantic v2
  • SQLAlchemy 2.x
  • Docker
  • Kubernetes

Real-world production context

In production, a Python backend like this rarely runs as a single uvicorn process on a laptop. Teams build the app into a container image, push it to a registry, and run it behind a managed load balancer with autoscaling, health checks and centralized logging. Async FastAPI services typically use multiple Uvicorn workers managed by Gunicorn, a managed Postgres for state, Redis for cache and rate-limit counters, and an object store for uploads. The reason cloud hosting becomes a hard requirement is operational: zero-downtime rollouts, log aggregation, metrics, and TLS at the edge are not optional once real users depend on the API.

Recommended tools & deployment options

Once the tutorial works on your machine, the next question is *where do I run this for real?* These are the platforms most Python backend teams reach for:

  • DigitalOcean — the simplest path from a working FastAPI container to a public URL. App Platform deploys directly from a Dockerfile, managed Postgres and Redis are one click away, and pricing is predictable. A common way to deploy the setup in this tutorial is using a cloud provider like DigitalOcean when you want to ship quickly without learning a full cloud SDK.
  • AWS — the default for enterprise workloads. ECS Fargate or EKS run containers without you managing servers, RDS handles Postgres, and CloudWatch covers logs and metrics.
  • Docker — the packaging format every modern deploy target understands. Build once, run the same image locally, in CI and in production.
  • Kubernetes (managed: EKS, DOKS, GKE) — the right choice once you have more than a handful of services, need rolling updates, autoscaling and policy-driven networking.

A VPS or managed cloud service is required to run this architecture end-to-end — uvicorn --reload is for development, not for serving traffic.

FAQ

Sessions vs JWT? Server-side sessions with Redis are simpler and revocable. Prefer JWT when you have multiple services that need stateless verification.

Next steps & related tutorials

Keep the momentum going with the next tutorial in this learning path:

Architecture

JWT Authentication Flow

CLIENTSECURITY FILTERAUTH LAYERPROTECTED APIDATABearer <jwt>/loginverify pwdissue JWTvalid tokenClientWeb / MobileJWT FilterVerify SignatureAuth Controller/login /refreshToken ServiceIssue · VerifyUser ServiceBCrypt HashProtected Controller@PreAuthorizeUsers DBPostgreSQLSigning KeyHS256 / RS256
Login returns a signed JWT; subsequent requests carry the token in the Authorization header and a filter validates it before reaching protected endpoints.

TL;DR

Key takeaways

  • Understand the core concepts behind JWT Authentication in FastAPI — Secure APIs Properly in a production context.
  • Apply the patterns to real Python & FastAPI systems, not just toy examples.
  • Recognize the trade-offs, failure modes, and operational concerns before adopting them.
  • Get a clear path to the next step — related tutorials, tools, and reference architectures.

Avoid these

Common mistakes

  • 1. Copy-pasting code without understanding the trade-offs

    It's tempting to ship a snippet from a blog post into production, but Python & FastAPI patterns only work when the failure modes are understood. Always reason about timeouts, retries, and consistency.

  • 2. Skipping observability from day one

    Structured logs, metrics, and traces are not optional. Wire them in before you ship — debugging Python & FastAPI systems without them is painful and expensive.

  • 3. Optimizing too early

    Premature caching, sharding, or microservice extraction adds operational cost. Validate the bottleneck with real measurements first.

  • 4. Ignoring security defaults

    Secrets in env files, open management ports, missing RBAC — these are the most common production incidents. Treat security as part of the definition of done.

Ship it safely

Production best practices

Apply these before promoting JWT Authentication in FastAPI — Secure APIs Properly to a real production environment.

Scalability

Design Python & FastAPI services to scale horizontally. Keep request handlers stateless, push session and cache state to external stores (Redis, the database), and benchmark p95/p99 latency under realistic load before tuning.

Monitoring & Observability

Emit metrics (RED/USE), structured JSON logs, and distributed traces from day one. Wire dashboards and alerts to SLOs you actually care about — error rate, latency, saturation — not vanity metrics.

Logging

Log with correlation IDs, never log secrets or PII, and centralize logs (ELK, Loki, CloudWatch). Use levels deliberately: INFO for state changes, WARN for recoverable issues, ERROR for incidents.

Security

Apply least-privilege IAM, rotate secrets through a vault, validate every input, and patch dependencies on a schedule. For HTTP services, enable TLS everywhere and set sensible security headers.

Testing

Layer unit, integration, and contract tests. Run them in CI on every PR, and add smoke tests post-deploy. For Python & FastAPI systems, also run chaos and load tests before a major release.

Reliability & Rollouts

Ship with health checks, readiness probes, graceful shutdown, and a rollback strategy. Prefer canary or blue/green deploys over big-bang releases.

Questions

Frequently asked questions

Is this tutorial up to date?

Yes. This tutorial was last reviewed and updated on May 26, 2026. We revisit popular Python & FastAPI tutorials regularly to keep them aligned with current best practices.

What level is this tutorial aimed at?

It is written for working developers with some backend experience. Beginners can still follow along, and senior engineers will find production-grade patterns and trade-off discussions.

Do I need to follow every step in order?

The walkthrough is sequential because each step depends on the previous one. If you only need a specific concept, the table of contents at the top of the article lets you jump straight to that section.

Where can I find the source code?

Code samples are inlined in the tutorial. When a companion repository is published it will be linked at the top of this page.

Go deeper

Further reading

#FastAPI#JWT#Authentication#OAuth2#Security#Python

More From the Channel

Follow the full tutorial series on YouTube

The MasterLabSystems channel publishes in-depth, project-based tutorials on Java, Spring Boot, microservices, Docker, Kubernetes, AWS and DevOps — the same topics covered on this site, with full code walkthroughs.

Stay in the Loop

Get the next tutorial in your inbox

next tutorial →

FastAPI + Kafka — Build Real-Time Event Systems

Related tutorials