If you've ever built a web API, you've probably asked yourself: "How do I make sure only the right people can access certain routes?" That's exactly what authentication middleware solves — and in this guide, you'll learn how to do it in Axum 0.8 using JSON Web Tokens (JWT) .
By the end of this article, you'll understand:
What JWTs are and why they're useful
How middleware works in Axum 0.8
How to write a JWT auth middleware from scratch
How to protect routes and pass user data to your handlers
Let's get started.
What is a JWT?
A JSON Web Token (JWT) is a compact, self-contained string that carries information about a user. It looks like this:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0IiwiZXhwIjoxNzAwMDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Enter fullscreen mode
Exit fullscreen mode
It has three parts separated by dots:
Header — the algorithm used to sign the token (e.g. HS256 )
Payload — the actual data (e.g.…