Skip to main content / پرش به محتوای اصلی

Implementing Secure JWT Authentication in FastAPI (Access & Refresh Tokens)

November 20262 min read۰ بازدید
Step-by-step guide to secure JWT authentication in FastAPI: bcrypt password hashing, Access/Refresh token architecture, OAuth2PasswordBearer, and type-safe route protection.

Robust authentication and authorization architectures are central pillars of modern web backends. In modern Stateless REST APIs, JSON Web Tokens (JWT) serve as the industry standard: enabling secure identity verification without imposing stateful session lookups on central database engines.

In this comprehensive tutorial, we leverage FastAPI's dependency injection system and cryptographic standards to engineer an enterprise-grade authentication service featuring Access and Refresh token separation.

Short Answer: In FastAPI, securely hash inbound passwords with passlib[bcrypt], sign compact claims using PyJWT, and safeguard sensitive endpoints using OAuth2PasswordBearer wrapped in a reusable Depends(get_current_user) dependency.


Architecture Overview

  1. The client submits credentials to /auth/login.
  2. The backend verifies the password against stored bcrypt hashes.
  3. Upon verification, two tokens are issued:
    • Access Token: Short lifespan (15–30 minutes) carried inside Authorization: Bearer <token> headers.
    • Refresh Token: Long lifespan (7–30 days) used solely to obtain renewed access tokens.
  4. Protected routes verify cryptographic signatures via the shared SECRET_KEY.

1. Required Packages

bash
pip install "fastapi>=0.110.0" "pyjwt>=2.8.0" "passlib[bcrypt]>=1.7.4" python-dotenv

2. Security & Hashing Module (security.py)

python
import os
from datetime import datetime, timedelta, timezone
import jwt
from passlib.context import CryptContext
from dotenv import load_dotenv

load_dotenv()

SECRET_KEY = os.getenv("JWT_SECRET_KEY", "super-secret-key-change-in-production")
ALGORITHM = "HS256"
ACCESS_TOKEN_MINUTES = 30
REFRESH_TOKEN_DAYS = 7

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def hash_password(password: str) -> str:
    return pwd_context.hash(password)

def verify_password(plain: str, hashed: str) -> bool:
    return pwd_context.verify(plain, hashed)

def create_access_token(data: dict) -> str:
    payload = data.copy()
    expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_MINUTES)
    payload.update({"exp": expire, "type": "access"})
    return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)

def create_refresh_token(data: dict) -> str:
    payload = data.copy()
    expire = datetime.now(timezone.utc) + timedelta(days=REFRESH_TOKEN_DAYS)
    payload.update({"exp": expire, "type": "refresh"})
    return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)

def decode_token(token: str) -> dict:
    return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])

3. Protecting Routes via FastAPI Dependencies (main.py)

python
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from security import create_access_token, decode_token

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")

async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
    try:
        payload = decode_token(token)
        if payload.get("type") != "access":
            raise ValueError("Invalid token type")
        return payload
    except Exception:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid or expired token credentials",
        )

@app.get("/protected/dashboard")
async def view_dashboard(user: Annotated[dict, Depends(get_current_user)]):
    return {"status": "authorized", "user": user["sub"]}

Frequently Asked Questions

Can JWT tokens contain private user secrets?

No. JWT payload data is base64-encoded, not encrypted. Anyone can decode and inspect the JSON claims. Never embed passwords, API keys, or personally identifiable data inside JWT bodies.

How can a stateless token be revoked on logout?

Tokens can be placed on a Redis-backed Distributed Blacklist using their unique token ID (jti) with a TTL matching the token's remaining lifespan.

Tags for this article:

Enjoyed this article?

Share it with your friends and colleagues.

Share: