Auth middleware
Learn how to write an Axum auth middleware with middleware from_fn that verifies a JWT on every request and answers unauthenticated requests with 401
An auth middleware is a gate that stands in front of a handler and checks the request before the handler ever sees it. It reads the token from the request, verifies the token signature and expiry, and either passes the request on with the caller's identity attached or stops it with a 401 response. One function, written once, protects every route it is attached to.
Where This Fits
The earlier preview built the same gate with a hard-coded token string, so the shape of the middleware was visible without any real cryptography. That preview answered the question of where the check lives. This page replaces the comparison with a real verification step. The token is now a signed JWT, and the middleware calls the jsonwebtoken crate to check the signature and the expiry on every request. The shape stays the same, the check becomes real.
Think of a badge reader at the entrance of a building. The preview version compared the badge to a photocopy taped to the wall. This version scans the badge, checks the hologram that proves it was issued by the building, and checks the printed expiry date. A photocopied badge fails the scan, and an expired badge fails the date check, even if the name on it is right.
The Smallest Working Version
Create a project with the files below. The error type comes first, then the token code and the middleware, then the routes, then the entry point.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2.0"
jsonwebtoken = { version = "12", features = ["rust_crypto"] }
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
The jsonwebtoken dependency needs a crypto backend, which is a library that does the actual signing math. Version 12 of the crate does not pick one for you. The rust_crypto feature selects the pure Rust backend, so it builds with no C compiler and no extra tools. The other backend is aws_lc_rs, and the two cannot be enabled together. That feature line is not optional decoration. Leave it out and the build fails with an error about a missing crypto provider.
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde_json::json;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum AppError {
#[error("resource not found")]
NotFound,
#[error("{0}")]
ValidationError(String),
#[error("something went wrong")]
InternalError,
#[error("unauthorized")]
Unauthorized,
#[error("forbidden")]
Forbidden,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let status = match &self {
AppError::NotFound => StatusCode::NOT_FOUND,
AppError::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY,
AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
AppError::Unauthorized => StatusCode::UNAUTHORIZED,
AppError::Forbidden => StatusCode::FORBIDDEN,
};
let body = Json(json!({ "error": self.to_string() }));
(status, body).into_response()
}
}
pub type HandlerResult<T> = Result<T, AppError>;
Every error this project returns shares one shape. The status code changes, the body is always a JSON object with a single error field, and the message is a single short word. The auth middleware returns AppError::Unauthorized for every failed check, so an unauthenticated request gets status 401 and the body {"error":"unauthorized"}.
use std::time::{SystemTime, UNIX_EPOCH};
use axum::{
extract::Request,
http::header,
middleware::Next,
response::Response,
};
use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation, decode, encode};
use serde::{Deserialize, Serialize};
use crate::errors::AppError;
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
pub sub: i32,
pub role: String,
pub exp: usize,
}
#[derive(Debug, Clone)]
pub struct AuthUser {
pub user_id: i32,
pub role: String,
}
pub fn jwt_secret() -> String {
std::env::var("JWT_SECRET")
.unwrap_or_else(|_| "test-secret-only-for-local-development".to_string())
}
pub fn now_seconds() -> usize {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs() as usize
}
pub fn token_for(user_id: i32, role: &str) -> String {
token_for_with_expiry(user_id, role, now_seconds() + 3600)
}
pub fn token_for_with_expiry(user_id: i32, role: &str, exp: usize) -> String {
let claims = Claims {
sub: user_id,
role: role.to_string(),
exp,
};
let key = EncodingKey::from_secret(jwt_secret().as_bytes()).unwrap();
encode(&Header::default(), &claims, &key).unwrap()
}
pub fn bearer_token(request: &Request) -> Option<&str> {
request
.headers()
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
}
pub fn verify_token(token: &str) -> Result<Claims, AppError> {
let key = DecodingKey::from_secret(jwt_secret().as_bytes())
.map_err(|_| AppError::Unauthorized)?;
decode::<Claims>(token, &key, &Validation::default())
.map(|data| data.claims)
.map_err(|_| AppError::Unauthorized)
}
pub async fn auth_middleware(
mut request: Request,
next: Next,
) -> Result<Response, AppError> {
let Some(token) = bearer_token(&request) else {
return Err(AppError::Unauthorized);
};
let claims = verify_token(token)?;
request.extensions_mut().insert(AuthUser {
user_id: claims.sub,
role: claims.role,
});
Ok(next.run(request).await)
}
Claims is the data carried inside the token. The field sub is the user id, a plain integer, and role is a string that is either "user" or "admin". The field exp is the expiry time, counted in seconds since the start of 1970, which is the standard way computers count time. AuthUser is the smaller value the handler receives after verification, just the user id and the role, with no expiry and no token attached.
token_for is a helper for making test tokens while learning. It builds a Claims value that expires one hour from now and signs it with the secret. It exists so the examples on this page can be run and tested. It is not a login handler, and it must never appear in a real application, because any code that mints tokens without checking a password hands out access to anyone who calls it.
pub mod auth;
pub mod errors;
use axum::{
Json, Router,
extract::Extension,
middleware,
routing::get,
};
use serde_json::json;
use auth::{AuthUser, auth_middleware};
use errors::AppError;
pub fn app() -> Router {
let protected = Router::new()
.route("/me", get(me_handler))
.route_layer(middleware::from_fn(auth_middleware));
Router::new()
.route("/public", get(public_handler))
.merge(protected)
}
async fn public_handler() -> &'static str {
"Anyone can read this."
}
async fn me_handler(
Extension(user): Extension<AuthUser>,
) -> Result<Json<serde_json::Value>, AppError> {
Ok(Json(json!({ "user_id": user.user_id, "role": user.role })))
}
The router is built in two parts. The protected router holds /me and carries the auth middleware through route_layer, which attaches the middleware only to the routes already in that router. The outer router holds /public and merges the protected router in. A request to /public never meets the middleware. A request to /me always does.
use axum_project::app;
#[tokio::main]
async fn main() {
let app = app();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run the server with a test secret set in the environment:
JWT_SECRET=test-secret-only-for-local-development cargo run
The string test-secret-only-for-local-development is a throwaway secret for local practice. It must never be used anywhere real, because anyone who has read this page knows it, and a token signed with a known secret is worth nothing.
The test secret is public knowledge:
The fallback inside jwt_secret exists only so the learning examples run without extra setup. A real deployment must set JWT_SECRET to a long random value that nobody else knows, and must fail loudly if the variable is missing, instead of falling back to a known string. The strict version looks like this, and it belongs in any code that leaves your machine: std::env::var("JWT_SECRET").expect("JWT_SECRET must be set").
To call the protected route you need a token first. The project includes a small example program that prints one. It lives in examples/make_token.rs:
use axum_project::auth::token_for;
fn main() {
let role = std::env::args().nth(1).unwrap_or_else(|| "user".to_string());
let user_id: i32 = std::env::args()
.nth(2)
.and_then(|value| value.parse().ok())
.unwrap_or(7);
println!("{}", token_for(user_id, &role));
}
Run it with the same secret, passing the role and the user id:
JWT_SECRET=test-secret-only-for-local-development cargo run --example make_token -- user 7
The terminal prints a long token with two dots in it. Copy it and use it in the requests below. The public route answers without a token:
curl http://127.0.0.1:3000/public
Anyone can read this.
The protected route without a token answers 401:
curl -i http://127.0.0.1:3000/me
HTTP/1.1 401 Unauthorized
content-type: application/json
content-length: 24
{"error":"unauthorized"}
With a bad token the answer is the same 401, because the middleware cannot tell a forged token from a mistyped one, and it does not try:
curl -i -H "Authorization: Bearer this.is.not.a.token" http://127.0.0.1:3000/me
HTTP/1.1 401 Unauthorized
content-type: application/json
content-length: 24
{"error":"unauthorized"}
With the token from the example program, replacing TOKEN with the printed value, the handler answers with the user the token describes:
curl -H "Authorization: Bearer TOKEN" http://127.0.0.1:3000/me
{"role":"user","user_id":7}
Working Setup:
If the public route answers without a token, the protected route answers 401 without one and 401 with a bad one, and the same route answers 200 with the user id and role when the token is valid, the middleware is wired up correctly. Those four outcomes are the whole contract of this page.
Understanding the Middleware Function Line by Line
The middleware is short, and each of its lines does one job. A beginner who understands these lines understands every auth middleware built from this shape.
The function signature
pub async fn auth_middleware(
mut request: Request,
next: Next,
) -> Result<Response, AppError> {
The function is async because from_fn requires an async function. It takes the incoming Request, which is the full HTTP request with its method, path, headers, and body, and a Next value, which stands for everything inside this middleware, the layers below it and the handler at the end. The request parameter is mut, short for mutable, because the function changes the request later by inserting the user into it. The return type is Result<Response, AppError>. A success value is the response from the handler. A failure value is an AppError, which Axum turns into a response through its IntoResponse implementation. That is what makes the ? operator usable inside the function, and what makes return Err(AppError::Unauthorized) produce a proper 401 response instead of a compiler error.
The Request type comes from axum::extract, which is the import to use in middleware. A bare http::Request from the http crate needs a body type parameter and does not work as a plain parameter type here.
Pulling the token out of the header
let Some(token) = bearer_token(&request) else {
return Err(AppError::Unauthorized);
};
The token travels in the Authorization header, in the form Bearer <token>, where Bearer is the scheme name that marks the value as a bearer token, a token the holder simply presents to prove who they are. The bearer_token helper reads that header, turns the value into text, and strips the Bearer prefix, returning an Option, a value that is either present or absent. When the helper returns nothing, the request has no usable token, and the middleware returns the unauthorized error at once. The handler never runs, and the let ... else syntax keeps the rest of the function free of nesting.
Verifying the token
let claims = verify_token(token)?;
This is the line that does the security work. The ? operator means that when verify_token fails, the error returns from the middleware immediately, and the lines below never run. When it succeeds, claims holds the verified contents of the token, and the code below can trust them. There is no path through this function where unverified data reaches the handler.
Attaching the user to the request
request.extensions_mut().insert(AuthUser {
user_id: claims.sub,
role: claims.role,
});
Extensions are a type-keyed storage area attached to each request, where a value is stored under its own type. The middleware inserts an AuthUser built from the verified claims, so the handler can ask for it later. The insert happens before next.run, so the handler sees the value. The AuthUser type must derive Clone, because the Extension extractor requires the stored type to be cloneable. Only the user id and the role are carried forward. The raw token string and the expiry time stay behind in the middleware, because the handler has no use for them.
Passing the request onward
Ok(next.run(request).await)
next.run(request).await hands the request to the rest of the stack and waits for the response. The middleware returns that response wrapped in Ok. Everything before this line is the request gate, and everything after it would be the response path. This middleware does nothing after the call, because its whole job is the gate. A missing next.run on the success path would mean the handler never runs, and the client would get whatever the middleware returned instead.
What decode Actually Checks
The verify_token function is three arguments and one call, and the call does more than it looks like it does.
pub fn verify_token(token: &str) -> Result<Claims, AppError> {
let key = DecodingKey::from_secret(jwt_secret().as_bytes())
.map_err(|_| AppError::Unauthorized)?;
decode::<Claims>(token, &key, &Validation::default())
.map(|data| data.claims)
.map_err(|_| AppError::Unauthorized)
}
decode is the verify step from the jsonwebtoken crate. It takes the token string, a decoding key built from the secret, and a Validation value that states the rules. It returns the decoded data on success, which has two fields, the token header and the claims, and .map(|data| data.claims) keeps only the claims. On any failure it returns an error, and .map_err(|_| AppError::Unauthorized) turns every kind of failure into the same unauthorized variant, deliberately discarding the detail.
One line in that function deserves a closer look. DecodingKey::from_secret returns a Result in version 12 of the crate, not a bare key, because building a key from a secret can fail. The let key = ... line handles that failure by mapping it to the unauthorized variant, exactly like a failed verification. The same applies on the minting side. EncodingKey::from_secret also returns a Result, and the test helper unwraps it, because a helper that only runs in tests may panic on a bad secret, while the verification path must answer with a clean 401 instead.
The checks inside decode are the reason the middleware is safe to trust. First, it checks the signature, which is the cryptographic seal on the token. The signature is computed from the token contents and the secret, so a token whose contents were changed after signing, or a token signed with a different secret, fails this check. Second, it checks the expiry. Validation::default() requires the exp claim to be present and rejects the token when the current time is past it, so an old token stops working on its own. Third, it only accepts the HS256 algorithm by default, which is the signing algorithm that uses a shared secret. A token that claims a different algorithm is rejected instead of being verified with the wrong method.
One generic error for every verification failure:
The .map_err(|_| AppError::Unauthorized) line throws away the reason the token failed, and that is deliberate. A response that says "token expired" for one failure and "bad signature" for another teaches an attacker how the check works. The detail belongs in the server log, where the developer can read it, not in the response, where anyone can read it. When debugging, log the error inside verify_token before mapping it away, and keep the response generic.
The expiry check deserves a plain sentence about time. exp is counted in seconds since the start of 1970, and decode compares it against the server clock. A token minted with exp one hour ahead works for one hour and then fails, with no action from the server. A token whose exp is already in the past fails at once. The test section below mints an expired token on purpose to prove this.
The Concept Behind the Gate
A middleware sits between the router and the handler. The router has already matched the path, so the middleware knows which route the request is heading for. The handler has not run yet, so the middleware can still stop the request cheaply, before any real work happens. That position is what makes middleware the right home for authentication. The check runs once, in one place, and every protected handler behind it is covered without repeating the check.
The mental model from the preview still holds, with one change. The bouncer at the door now scans the badge instead of comparing it to a photocopy. The visitor slip the bouncer hands to the front desk is the AuthUser in the request extensions. The desk, which is the handler, reads the slip with Extension<AuthUser> and knows who it is serving, without ever seeing the badge itself.
Why This Design
Putting the check in middleware instead of in each handler has three concrete effects. First, a protected handler never has to remember to check. The route table shows the protection, because the middleware is attached where the route is defined, and a handler that forgets the check cannot exist, because the handler never sees an unchecked request. Second, the check runs before the handler does any work, so an unauthenticated request costs the server almost nothing and reveals nothing about whether the requested data exists. Third, changing the check touches one function. Replacing the token scheme, changing the secret source, or adding logging to rejections all happen in auth_middleware, and every protected route picks the change up at once.
The alternative is a helper called on the first line of every handler. That works for a small project, and it is the shape the error pages used, but it has a failure mode middleware does not have. A new handler written in a hurry can forget the call, and the compiler will not complain, because a handler without a check is still a valid handler. A route without its middleware is visible in the router wiring, and a test that calls the route without a token catches it at once.
A Richer Complete Example
The smallest version protects one route. A realistic version protects several, and the same middleware covers all of them without any new check code. Add a settings route to the protected router and a second public route to the outer router:
pub mod auth;
pub mod errors;
use axum::{
Json, Router,
extract::Extension,
middleware,
routing::get,
};
use serde_json::json;
use auth::{AuthUser, auth_middleware};
use errors::AppError;
pub fn app() -> Router {
let protected = Router::new()
.route("/me", get(me_handler))
.route("/settings", get(settings_handler))
.route_layer(middleware::from_fn(auth_middleware));
Router::new()
.route("/", get(home_handler))
.route("/public", get(public_handler))
.merge(protected)
}
async fn home_handler() -> &'static str {
"Welcome. Sign in to see your profile."
}
async fn public_handler() -> &'static str {
"Anyone can read this."
}
async fn me_handler(
Extension(user): Extension<AuthUser>,
) -> Result<Json<serde_json::Value>, AppError> {
Ok(Json(json!({ "user_id": user.user_id, "role": user.role })))
}
async fn settings_handler() -> Json<serde_json::Value> {
Json(json!({ "theme": "dark", "language": "en" }))
}
Nothing in the middleware changed. The protected router gained a route, and the middleware covers it because route_layer wraps every route already in the router when it is called. The settings handler does not even ask for the AuthUser, because it serves the same settings to every signed-in user, but it is still protected, because the middleware runs before it. A request to /settings without a token gets 401, and a request with a valid token gets the settings. The public routes stay open, because they live on the outer router, outside the protected one.
Try the new route with the token from the example program:
curl -H "Authorization: Bearer TOKEN" http://127.0.0.1:3000/settings
{"language":"en","theme":"dark"}
And without a token:
curl -i http://127.0.0.1:3000/settings
HTTP/1.1 401 Unauthorized
content-type: application/json
content-length: 24
{"error":"unauthorized"}
The handler decides what the user sees, the middleware decides whether they get in:
The settings handler ignores the AuthUser entirely, and that is fine. Protection and personalisation are separate jobs. The middleware answers whether the request may proceed. The handler answers what the response contains, and it reads the user only when the response depends on who is asking.
Variations on the Middleware
One shape does not fit every project, and the variations below each change one decision while keeping the gate in the same place.
A check-only middleware that inserts nothing
Some routes only need to know that the caller is signed in, and no handler reads the user. The middleware can skip the insert and keep only the verification:
pub async fn require_signed_in(
request: Request,
next: Next,
) -> Result<Response, AppError> {
let Some(token) = bearer_token(&request) else {
return Err(AppError::Unauthorized);
};
verify_token(token)?;
Ok(next.run(request).await)
}
The request parameter no longer needs mut, because nothing is inserted into it. The verify_token(token)? line still rejects bad tokens, and the verified claims are discarded, because nothing downstream needs them. Use this shape when the protected handlers serve the same data to every signed-in user. Use the full shape, with the insert, as soon as any handler needs the user id or the role.
Passing the secret through state instead of reading the environment
Reading the environment variable inside the middleware is simple, and it keeps the middleware function to two parameters. When the secret comes from somewhere else, such as a config value loaded at startup, the stateful form carries it in. The function takes the secret as its first argument, and the layer is built with the secret attached:
use axum::extract::State;
pub async fn auth_middleware_with_state(
State(secret): State<String>,
mut request: Request,
next: Next,
) -> Result<Response, AppError> {
let Some(token) = bearer_token(&request) else {
return Err(AppError::Unauthorized);
};
let key = DecodingKey::from_secret(secret.as_bytes())
.map_err(|_| AppError::Unauthorized)?;
let claims = decode::<Claims>(token, &key, &Validation::default())
.map(|data| data.claims)
.map_err(|_| AppError::Unauthorized)?;
request.extensions_mut().insert(AuthUser {
user_id: claims.sub,
role: claims.role,
});
Ok(next.run(request).await)
}
Attach it with from_fn_with_state, passing the secret at the point where the layer is built:
let secret = jwt_secret();
let protected = Router::new()
.route("/me", get(me_handler))
.route_layer(middleware::from_fn_with_state(
secret,
auth_middleware_with_state,
));
The plain from_fn form cannot extract State, because it has no state to give. That is a documented limit, not a bug, and from_fn_with_state exists for exactly this case. The environment-variable form on this page is the simpler of the two, and the state form is the better one when the secret is loaded once at startup and shared with other parts of the app.
Returning a plain response instead of a result
When every failure is the same status and the same body, Result<Response, AppError> is the compact shape. When different failures need different bodies, returning a Response directly gives more control:
use axum::{http::StatusCode, response::IntoResponse};
pub async fn auth_middleware_response(
mut request: Request,
next: Next,
) -> Response {
let Some(token) = bearer_token(&request) else {
return (StatusCode::UNAUTHORIZED, "missing or invalid token").into_response();
};
let Ok(claims) = verify_token(token) else {
return (StatusCode::UNAUTHORIZED, "missing or invalid token").into_response();
};
request.extensions_mut().insert(AuthUser {
user_id: claims.sub,
role: claims.role,
});
next.run(request).await
}
This version returns the same status for both failures, but with a plain text body instead of the shared JSON shape. It breaks the contract that every error in the project uses {"error": "..."}, so it is shown here as a shape to recognise, not as the recommended one for this project. The Result form keeps the shared shape automatically, because the error travels through AppError::into_response, and that is why the rest of this page uses it.
A Plain Text Diagram of the Flow
The request meets the middleware before the handler, and the two outcomes split at the verification step.
request arrives with Authorization header
|
v
bearer_token: is a Bearer token present?
|
+-- no --> AppError::Unauthorized
| |
| v
| 401 + {"error": "unauthorized"}
|
+-- yes --> verify_token: signature and expiry valid?
|
+-- no --> AppError::Unauthorized
| |
| v
| 401 + {"error": "unauthorized"}
|
+-- yes --> insert AuthUser into extensions
|
v
next.run(request)
|
v
handler builds the response
|
v
200 + {"user_id": 7, "role": "user"}
The diagram has two rejection branches and one success branch, and both rejections end in the same answer. That sameness is a feature. A client sees one response for every authentication failure, and an attacker learns nothing from probing the difference.
Testing It
The tests below send requests straight through the router with oneshot, which is a test helper that runs one request through a service without any network connection. No server needs to be running, and no token needs to be copied from a terminal. The helper builds a request with or without a token, and each test checks the status and the exact body.
use axum::{
body::{Body, to_bytes},
http::{Request, StatusCode},
};
use axum_project::{app, auth::{now_seconds, token_for, token_for_with_expiry}};
use tower::ServiceExt;
async fn body_text(response: axum::response::Response) -> String {
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
String::from_utf8(bytes.to_vec()).unwrap()
}
async fn get(uri: &str, token: Option<&str>) -> (StatusCode, String) {
let mut builder = Request::builder().uri(uri);
if let Some(token) = token {
builder = builder.header("authorization", format!("Bearer {token}"));
}
let response = app()
.oneshot(builder.body(Body::empty()).unwrap())
.await
.unwrap();
let status = response.status();
(status, body_text(response).await)
}
#[tokio::test]
async fn public_without_token_is_ok() {
let (status, body) = get("/public", None).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, "Anyone can read this.");
}
#[tokio::test]
async fn me_without_token_is_unauthorized() {
let (status, body) = get("/me", None).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, r#"{"error":"unauthorized"}"#);
}
#[tokio::test]
async fn me_with_bad_token_is_unauthorized() {
let (status, body) = get("/me", Some("this.is.not.a.token")).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, r#"{"error":"unauthorized"}"#);
}
#[tokio::test]
async fn me_with_expired_token_is_unauthorized() {
let token = token_for_with_expiry(7, "user", now_seconds() - 3600);
let (status, body) = get("/me", Some(&token)).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, r#"{"error":"unauthorized"}"#);
}
#[tokio::test]
async fn me_with_valid_token_returns_user() {
let token = token_for(7, "user");
let (status, body) = get("/me", Some(&token)).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, r#"{"role":"user","user_id":7}"#);
}
The expired-token test is the one that guards the expiry check. It mints a token whose exp is one hour in the past. The test uses a full hour rather than a few seconds because Validation::default() allows 60 seconds of leeway for clock skew, so a token that expired only a moment ago may still pass, while a token an hour past expiry always fails. If somebody later replaces decode with a call that skips validation, that test fails, because the expired token would suddenly be accepted. The bad-token test guards the signature check in the same way.
Run the tests with:
cargo test
The tower crate is needed as a dev dependency for oneshot, and it is already in the Cargo.toml above under [dev-dependencies].
Tests mint their own tokens:
The tests call token_for directly instead of copying a token from the terminal, because a token minted in the test is always fresh, while a token pasted from a terminal expires an hour after it was printed. A test that depends on a pasted token starts failing for no reason the code can explain.
Common Beginner Mistakes
Comparing the token to a string instead of verifying it
// Wrong - a copied token passes, and any token with the right text passes
if token == "some-known-token" {
Ok(next.run(request).await)
} else {
Err(AppError::Unauthorized)
}
A string comparison accepts any token whose text matches, and it never checks a signature or an expiry. It is the preview shape, and it must not survive into real code. The fix is the decode call in verify_token, which checks the signature against the secret and the expiry against the clock.
Reading the claims without verifying the signature
// Wrong - decode_header reads the token without checking anything
let header = jsonwebtoken::decode_header(token)?;
The decode_header function reads only the token header, and it performs no signature verification and validates no claims. Splitting the token on dots and base64-decoding the middle part has the same flaw. The payload of a JWT is readable by anyone, by design, and reading it proves nothing about who wrote it. Only decode, with the secret and a Validation, proves the token was signed by someone who knows the secret and has not expired. Never build an AuthUser from an unverified payload.
Forgetting the space after Bearer
// Wrong - strip_prefix needs the space, or the token keeps a leading space
.and_then(|value| value.strip_prefix("Bearer"))
The header value is Bearer <token> with a space between the scheme and the token. Stripping Bearer without the space leaves a token that starts with a space, and no real token starts with a space, so verification fails for every request, including the ones with a valid token. The fix is strip_prefix("Bearer "), with the space included. A related mistake is comparing the whole header value to the bare token, which never matches, because the header value includes the scheme.
Calling next.run before verifying
// Wrong - the handler runs first, and the check happens too late
let response = next.run(request).await;
if bearer_token(&request).is_none() {
return Err(AppError::Unauthorized);
}
Ok(response)
This version does not even compile, because the request moves into next.run and cannot be read afterwards, and the compiler stops it. The deeper mistake is the order it attempts. A check that runs after the handler has already done its work is not a gate. The verification must finish before next.run is called, on every path through the function.
Using unwrap on the header lookup
// Wrong - a missing header panics instead of answering 401
let header = request.headers().get("authorization").unwrap();
A missing header is normal, not exceptional. It is the most common case for an unauthenticated request. Unwrapping it panics, and a panic inside middleware closes the connection without a clean response. The Option chain in bearer_token turns a missing header into a clean 401, which is the answer the client can act on.
Inserting the user with the wrong type
// Wrong - the handler asks for Extension<AuthUser> and finds nothing
request.extensions_mut().insert(claims);
The extensions map is keyed by type, so the value inserted must be exactly the type the handler asks for. Inserting the raw Claims while the handler asks for AuthUser means the handler finds nothing, and Axum answers the request with a 500 status. The compiler does not catch this, because both types are valid values to insert. The fix is to build the AuthUser from the claims, as the working version does, and to test the happy path with a real request rather than trusting the types alone.
A short-circuit that still calls next.run is not a short-circuit:
The most consequential mistake on this page is a guard that returns an error response on one path but still falls through to next.run. The handler runs, the protected data goes out, and the 401 never reaches the client. Always test the guarded route without credentials and confirm the handler body is absent from the response.
Final Complete Example
Here is the full project from this page, with the error type, the token code, the middleware, two protected routes, and the token-printing example.
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde_json::json;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum AppError {
#[error("resource not found")]
NotFound,
#[error("{0}")]
ValidationError(String),
#[error("something went wrong")]
InternalError,
#[error("unauthorized")]
Unauthorized,
#[error("forbidden")]
Forbidden,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let status = match &self {
AppError::NotFound => StatusCode::NOT_FOUND,
AppError::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY,
AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
AppError::Unauthorized => StatusCode::UNAUTHORIZED,
AppError::Forbidden => StatusCode::FORBIDDEN,
};
let body = Json(json!({ "error": self.to_string() }));
(status, body).into_response()
}
}
pub type HandlerResult<T> = Result<T, AppError>;
use std::time::{SystemTime, UNIX_EPOCH};
use axum::{
extract::Request,
http::header,
middleware::Next,
response::Response,
};
use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation, decode, encode};
use serde::{Deserialize, Serialize};
use crate::errors::AppError;
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
pub sub: i32,
pub role: String,
pub exp: usize,
}
#[derive(Debug, Clone)]
pub struct AuthUser {
pub user_id: i32,
pub role: String,
}
pub fn jwt_secret() -> String {
std::env::var("JWT_SECRET")
.unwrap_or_else(|_| "test-secret-only-for-local-development".to_string())
}
pub fn now_seconds() -> usize {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs() as usize
}
pub fn token_for(user_id: i32, role: &str) -> String {
token_for_with_expiry(user_id, role, now_seconds() + 3600)
}
pub fn token_for_with_expiry(user_id: i32, role: &str, exp: usize) -> String {
let claims = Claims {
sub: user_id,
role: role.to_string(),
exp,
};
let key = EncodingKey::from_secret(jwt_secret().as_bytes()).unwrap();
encode(&Header::default(), &claims, &key).unwrap()
}
pub fn bearer_token(request: &Request) -> Option<&str> {
request
.headers()
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
}
pub fn verify_token(token: &str) -> Result<Claims, AppError> {
let key = DecodingKey::from_secret(jwt_secret().as_bytes())
.map_err(|_| AppError::Unauthorized)?;
decode::<Claims>(token, &key, &Validation::default())
.map(|data| data.claims)
.map_err(|_| AppError::Unauthorized)
}
pub async fn auth_middleware(
mut request: Request,
next: Next,
) -> Result<Response, AppError> {
let Some(token) = bearer_token(&request) else {
return Err(AppError::Unauthorized);
};
let claims = verify_token(token)?;
request.extensions_mut().insert(AuthUser {
user_id: claims.sub,
role: claims.role,
});
Ok(next.run(request).await)
}
pub mod auth;
pub mod errors;
use axum::{
Json, Router,
extract::Extension,
middleware,
routing::get,
};
use serde_json::json;
use auth::{AuthUser, auth_middleware};
use errors::AppError;
pub fn app() -> Router {
let protected = Router::new()
.route("/me", get(me_handler))
.route("/settings", get(settings_handler))
.route_layer(middleware::from_fn(auth_middleware));
Router::new()
.route("/", get(home_handler))
.route("/public", get(public_handler))
.merge(protected)
}
async fn home_handler() -> &'static str {
"Welcome. Sign in to see your profile."
}
async fn public_handler() -> &'static str {
"Anyone can read this."
}
async fn me_handler(
Extension(user): Extension<AuthUser>,
) -> Result<Json<serde_json::Value>, AppError> {
Ok(Json(json!({ "user_id": user.user_id, "role": user.role })))
}
async fn settings_handler() -> Json<serde_json::Value> {
Json(json!({ "theme": "dark", "language": "en" }))
}
use axum_project::app;
#[tokio::main]
async fn main() {
let app = app();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
use axum_project::auth::token_for;
fn main() {
let role = std::env::args().nth(1).unwrap_or_else(|| "user".to_string());
let user_id: i32 = std::env::args()
.nth(2)
.and_then(|value| value.parse().ok())
.unwrap_or(7);
println!("{}", token_for(user_id, &role));
}
Run the checks with these commands.
JWT_SECRET=test-secret-only-for-local-development cargo check
JWT_SECRET=test-secret-only-for-local-development cargo test
JWT_SECRET=test-secret-only-for-local-development cargo run
Summary
The single decision that makes auth middleware work is the order of three lines. Verify the token first, attach the verified user second, call next.run third. Every failure mode on this page is a violation of that order. A token that is compared instead of verified, claims that are read before the signature is checked, a user that is attached from unverified data, or a handler that runs before the check finishes all break the same promise, that nothing behind the gate is reachable without proof.
That order is also the decision framework for the shapes that build on this page. When a route needs a different rule, such as only admins, the new rule goes in a second middleware that runs after this one, reading the AuthUser this one attached. When a route needs no check at all, it stays outside the protected router. The middleware never learns about roles or routes or permissions. It answers one question, is this token real, and it answers it the same way on every request.