惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
The Cloudflare Blog
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
V
Visual Studio Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 司徒正美
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
酷 壳 – CoolShell
酷 壳 – CoolShell
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
月光博客
月光博客
The GitHub Blog
The GitHub Blog
L
LangChain Blog
D
DataBreaches.Net
T
The Blog of Author Tim Ferriss
F
Fortinet All Blogs
博客园 - Franky
阮一峰的网络日志
阮一峰的网络日志
GbyAI
GbyAI
Apple Machine Learning Research
Apple Machine Learning Research
宝玉的分享
宝玉的分享
Engineering at Meta
Engineering at Meta
V
V2EX
MyScale Blog
MyScale Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
FastAPI for AI Engineers - Part 6: JWT Authentication in ...
Ananya S · 2026-06-16 · via DEV Community

In the previous article, we explored the concepts of Authentication and Authorization.

We learned that:

  • Authentication answers "Who are you?"
  • Authorization answers "What are you allowed to do?"

Understanding the concepts is important, but real-world applications require actual implementation.

If you've ever used Gmail, LinkedIn, GitHub, or ChatGPT, you've already used authentication systems countless times.

You enter your username and password, the application verifies your identity, and you gain access to protected resources.

But how does this actually work behind the scenes?

In this article, we'll build a complete JWT Authentication system using FastAPI.

If you haven't read the previous article, check it out first:


Why Do We Need Authentication?

Imagine building an AI-powered learning platform.

Without authentication:

  • Anyone could access any user's profile
  • Anyone could view another student's progress
  • Anyone could modify data belonging to other users

Clearly, this is a security problem.

Applications need a way to:

  1. Verify user identity
  2. Protect sensitive resources
  3. Allow users to stay logged in

This is where JWT Authentication comes in.


What is JWT?

JWT stands for JSON Web Token.

A JWT is a secure token that contains information about a user.

Instead of sending a username and password with every request, the user sends a token.

Typical flow:

Register User
      ↓
   Login
      ↓
Verify Credentials
      ↓
Generate JWT Token
      ↓
Access Protected Routes


Installing Required Packages

pip install python-jose passlib[bcrypt]

We'll use:

  • passlib for password hashing
  • python-jose for JWT token generation and verification

Step 1: Hashing Passwords

Storing passwords in plain text is extremely dangerous.

Never do this:

users = {
    "rahul": "password123"
}

If the database is compromised, every user's password becomes visible.

Instead, we store a hashed version.


Creating a Password Hasher

from passlib.context import CryptContext

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

What is CryptContext?

CryptContext manages password hashing algorithms.

In this example:

schemes=["bcrypt"]

we tell FastAPI to use the bcrypt hashing algorithm.


Hashing a Password

hashed_password = pwd_context.hash("password123")

print(hashed_password)

Output:

$2b$12$.....

Notice that the original password is no longer visible.


Verifying Passwords

When the user logs in:

pwd_context.verify(
    "password123",
    hashed_password
)

returns:

True

This allows us to verify passwords without storing them in plain text.


Step 2: User Registration

Let's create a simple registration endpoint.

from fastapi import FastAPI

app = FastAPI()

users = {}

@app.post("/register")
def register(username: str, password: str):

    hashed_password = pwd_context.hash(password)

    users[username] = hashed_password

    return {"message": "User registered successfully"}

What happens here?

  1. User submits username and password
  2. Password is hashed
  3. Hash is stored instead of the original password

Step 3: User Login

Now let's verify credentials.

@app.post("/login")
def login(username: str, password: str):

    stored_password = users.get(username)

    if not stored_password:
        return {"message": "User not found"}

    if not pwd_context.verify(password, stored_password):
        return {"message": "Invalid credentials"}

    return {"message": "Login successful"}

At this point, users can log in successfully.

However, they still need to send their username and password with every request.

JWT solves this problem.


Step 4: Creating a JWT Token

from jose import jwt
from datetime import datetime, timedelta

SECRET_KEY = "mysecretkey"

ALGORITHM = "HS256"

Why do we need a secret key?

The secret key is used to sign tokens.

If someone modifies the token, the signature becomes invalid.


Generate Token Function

def create_access_token(data: dict):

    to_encode = data.copy()

    expire = datetime.utcnow() + timedelta(minutes=30)

    to_encode.update({"exp": expire})

    encoded_jwt = jwt.encode(
        to_encode,
        SECRET_KEY,
        algorithm=ALGORITHM
    )

    return encoded_jwt

What does this function do?

  1. Copies user data
  2. Adds an expiry time
  3. Creates a signed JWT token
  4. Returns the token

Step 5: Generate Token During Login

@app.post("/login")
def login(username: str, password: str):

    stored_password = users.get(username)

    if not stored_password:
        return {"message": "User not found"}

    if not pwd_context.verify(password, stored_password):
        return {"message": "Invalid credentials"}

    token = create_access_token(
        {"sub": username}
    )

    return {
        "access_token": token,
        "token_type": "bearer"
    }

Successful login now returns:

{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "token_type": "bearer"
}


Step 6: Protected Route

Now we can protect routes.

@app.get("/profile")
def get_profile():

    return {
        "message": "Protected profile data"
    }

Currently anyone can access it.

In production applications, FastAPI verifies the JWT token before allowing access.

We'll implement complete route protection in the next article.

For now, focus on understanding:

  1. Registration
  2. Password Hashing
  3. Password Verification
  4. JWT Generation

These form the foundation of every authentication system.


Authentication Flow Recap

Register User
      ↓
Hash Password
      ↓
Store Hash
      ↓
   Login
      ↓
Verify Password
      ↓
Generate JWT
      ↓
Access Protected Routes


Final Thoughts

Today we built the core components of JWT Authentication:

  • User Registration
  • Password Hashing
  • Password Verification
  • JWT Token Generation

A user can now register, log in, and receive a signed JWT token.

However, generating a token is only half the story.

The next step is learning how to validate tokens and protect routes using FastAPI dependencies.

In the next article, we'll implement JWT-based route protection and begin exploring Role-Based Access Control (RBAC).