AuthUser extractor

Learn how a FromRequestParts extractor reads the Authorization header, verifies the token, and hands handlers a typed AuthUser with a user id and a role

An extractor is a function argument that Axum fills in from the incoming request, and AuthUser is an extractor that fills itself in from a verified token. A handler that takes AuthUser as an argument receives a typed value holding the user id and the role, and it receives nothing at all when the token is missing or bad, because the extractor rejects the request before the handler body runs. One argument, one verified identity, no header parsing inside the handler.

Where This Fits

The login step mints a token, and the verification step checks one. This page turns that check into an argument a handler can take. The pieces it joins are small, the header reading, the token verification, and the claims, and the result is the thing protected routes take as their first argument. A handler that needs to know who is asking takes AuthUser, and a handler that does not need to know leaves it out.

Think of a doorkeeper with a guest list. A guest shows an invitation, the doorkeeper checks the seal and reads the name off it, and then opens the door and tells the host who has arrived. The host never checks the invitation, because the doorkeeper already did. The extractor is the doorkeeper, and the handler is the host.

The Smallest Working Version

Create a project with the same files as the login page, and add the extractor to src/auth.rs plus one route that takes it. The route is a profile that answers with the user id and the role from the token.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.9", features = ["runtime-tokio", "postgres", "macros", "derive"] }
jsonwebtoken = { version = "12", features = ["rust_crypto"] }
argon2 = "0.6"
thiserror = "2.0"

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
src/auth.rs
use axum::{
    extract::FromRequestParts,
    http::{HeaderMap, header, request::Parts},
};
use jsonwebtoken::{DecodingKey, Validation, decode};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;

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 verify_token(token: &str, secret: &str) -> Result<Claims, AppError> {
    let key = DecodingKey::from_secret(secret.as_bytes()).map_err(|error| {
        eprintln!("decoding key error: {error}");
        AppError::Unauthorized
    })?;
    let data = decode::<Claims>(token, &key, &Validation::default()).map_err(|error| {
        eprintln!("token decode error: {error}");
        AppError::Unauthorized
    })?;
    Ok(data.claims)
}

pub fn bearer_token(headers: &HeaderMap) -> Option<&str> {
    headers
        .get(header::AUTHORIZATION)
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.strip_prefix("Bearer "))
}

impl FromRequestParts<PgPool> for AuthUser {
    type Rejection = AppError;

    async fn from_request_parts(
        parts: &mut Parts,
        _state: &PgPool,
    ) -> Result<Self, Self::Rejection> {
        let Some(token) = bearer_token(&parts.headers) else {
            return Err(AppError::Unauthorized);
        };
        let secret = std::env::var("JWT_SECRET").map_err(|_| AppError::Unauthorized)?;
        let claims = verify_token(token, &secret)?;
        Ok(AuthUser {
            user_id: claims.sub,
            role: claims.role,
        })
    }
}

AuthUser is a plain struct with two public fields, the user id and the role, taken straight from the claims. It derives Clone so a handler can copy it when it needs the value in two places, and Debug so it prints readably in logs. It does not derive Serialize or Deserialize, because it is never turned into JSON and never parsed from JSON. It is built from verified claims, and only from verified claims.

bearer_token is a helper that pulls the token out of the headers and returns an Option, a value that is either present or absent. It is explained in full in the next section. verify_token is the verification helper from the previous subject: it builds a decoding key from the secret, decodes the token with the default validation, and returns the claims or the unauthorized variant.

The impl block is the extractor itself, and it is explained line by line below. Its rejection type is AppError, which is the shared error type, so a rejected request gets the shared JSON error body with status 401.

src/handlers.rs
use axum::Json;
use serde_json::json;

use crate::{
    auth::AuthUser,
    errors::HandlerResult,
};

pub async fn profile(user: AuthUser) -> HandlerResult<Json<serde_json::Value>> {
    Ok(Json(json!({ "user_id": user.user_id, "role": user.role })))
}

The handler takes AuthUser as its only argument, and its body is one line. By the time the body runs, the token has already been verified, so the handler trusts user.user_id and user.role without any further check. The response echoes both values back as JSON, which is what makes the demo below easy to read: the response shows exactly what the extractor handed the handler.

src/lib.rs
pub mod auth;
pub mod db;
pub mod errors;
pub mod handlers;

use axum::{Router, routing::get};
use handlers::profile;
use sqlx::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/profile", get(profile))
        .with_state(pool)
}
src/main.rs
use axum_project::{app, db::create_pool};

#[tokio::main]
async fn main() {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = create_pool(&database_url)
        .await
        .expect("failed to connect to the database");
    let router = app(pool);
    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, router).await.unwrap();
}

Start the server with the database URL and the signing secret, then log in to get a token, using the seeded user from the login page:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_jwt" JWT_SECRET="test-secret-only-for-local-development" cargo run
curl -X POST http://127.0.0.1:3000/login \
  -H "Content-Type: application/json" \
  -d '{"email": "ada@example.com", "password": "ada-secret-password"}'
{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsInJvbGUiOiJ1c2VyIiwiZXhwIjoxNzk0NjQ4MTU0fQ.Yytn5--kvv7H5_OXXodlwtqRzwdK_UcbdF5Wt9WbmYc"}

Send that token to the profile route in the Authorization header, which is the standard HTTP header for carrying credentials:

curl -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsInJvbGUiOiJ1c2VyIiwiZXhwIjoxNzk0NjQ4MTU0fQ.Yytn5--kvv7H5_OXXodlwtqRzwdK_UcbdF5Wt9WbmYc" http://127.0.0.1:3000/profile
{"role":"user","user_id":1}

The response carries the user id and the role from the token, and the order of the keys is alphabetical, because the JSON value sorts its keys. The extractor did the work, and the handler only echoed what it received. Without the header, the same route answers 401:

curl -i http://127.0.0.1:3000/profile
HTTP/1.1 401 Unauthorized
content-type: application/json
content-length: 24

{"error":"unauthorized"}

Working Setup:

If the request with the token returns 200 with the user id and the role, and the request without a token returns 401 with the body {"error":"unauthorized"}, the extractor is wired up correctly. The handler never runs for the second request, because the extractor rejects it first.

Understanding the Extractor Line by Line

The impl block is the part that is new, and each of its pieces does one job. A beginner who understands these pieces understands every custom extractor, because they all follow the same shape.

The trait and the state type

impl FromRequestParts<PgPool> for AuthUser {
    type Rejection = AppError;

FromRequestParts is the trait for extractors that read part of a request, such as the headers, without consuming the body. A trait is a set of methods a type promises to provide, and implementing it for AuthUser teaches Axum how to build an AuthUser from a request. The type parameter, PgPool, is the router state type, and it must match the state the router was built with, because Axum hands the extractor the state when it runs. This router holds a connection pool as its state, so the extractor declares PgPool, even though it never uses the pool. The pool is only there to satisfy the type, and the parameter is named _state with a leading underscore to mark it as intentionally unused.

type Rejection names the error the extractor returns when it cannot build the value. The rejection must implement IntoResponse, a trait that turns a value into an HTTP response, and AppError implements it, so a rejection becomes the shared JSON error body. A rejection type that did not implement it would fail to compile, and the compiler would say so plainly.

The State Type Must Match the Router:

The PgPool in FromRequestParts<PgPool> is not a free choice. It must be the same type the router was built with, because Axum hands the extractor the router state when it runs, and a mismatch means the extractor cannot be used on that router. A router built with a struct holding the pool and other values would need that struct type here instead, and the extractor would receive it as its second argument.

The method signature

    async fn from_request_parts(
        parts: &mut Parts,
        _state: &PgPool,
    ) -> Result<Self, Self::Rejection> {

Parts is the request split into its pieces: the method, the URI, the headers, and the extensions. The extractor takes a mutable reference to it, because reading the headers borrows them, and other extractors may need the same parts afterwards. The method is async, because the trait requires it, even though this extractor does no waiting. It returns a Result, with AuthUser on success and the rejection on failure, and Axum calls this method before the handler body runs.

Reading the header

        let Some(token) = bearer_token(&parts.headers) else {
            return Err(AppError::Unauthorized);
        };

The first step pulls the token out of the headers with the helper, and returns the unauthorized variant when there is none. The let ... else shape makes the intent plain: if there is no token, stop here. No token means no identity, and the request cannot proceed. The handler body never runs, and the client receives the generic 401.

Reading the secret

        let secret = std::env::var("JWT_SECRET").map_err(|_| AppError::Unauthorized)?;

The secret is read from the environment, and a missing variable maps to the unauthorized variant, not the internal error the login step used. The difference is the position of the check. At login, the server has already decided the user may log in, so a missing secret is the server failing its own job. Here, the server does not know who is asking yet, so a missing secret means no token can be verified, and the request fails closed with a 401. Failing closed means refusing the request when the server cannot prove it is safe, rather than letting it through.

Verifying and building AuthUser

        let claims = verify_token(token, &secret)?;
        Ok(AuthUser {
            user_id: claims.sub,
            role: claims.role,
        })
    }

verify_token checks the signature and the expiry, and the ? returns its unauthorized error early when the token fails. Only a verified token reaches the last lines, which copy the two claims into the struct. claims.sub, the user id from the token, becomes user_id, and claims.role becomes role. The exp claim is not copied, because the handler does not need it: the verification already proved the token is fresh, and the expiry has no further use once the check has passed.

The Bearer Token Helper, Piece by Piece

The helper is three chained calls, and each call handles one way the header can be wrong.

pub fn bearer_token(headers: &HeaderMap) -> Option<&str> {
    headers
        .get(header::AUTHORIZATION)
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.strip_prefix("Bearer "))
}

headers.get(header::AUTHORIZATION) looks up the header by its standard name and returns an Option, because the header might not be there at all. A HeaderMap is a collection of request headers, and header::AUTHORIZATION is the constant for the header name, which avoids a typo in a hand-written string. The next call, and_then(|value| value.to_str().ok()), turns the raw header value into text. A header value is bytes, and to_str fails when those bytes are not valid text, so ok() turns that failure into an absent value rather than an error. The last call, and_then(|value| value.strip_prefix("Bearer ")), removes the scheme prefix and returns the token itself, or an absent value when the prefix is not there.

The chain collapses every failure mode into the same absent value: a missing header, a non-text value, a wrong scheme, and an empty token all become None, and the extractor answers all of them with the same 401. That collapse is the same design as the login step, where every credential failure gets one answer, and it exists for the same reason: the client learns nothing about which part of the header was wrong.

The Scheme Match Is Case Sensitive:

The helper strips exactly Bearer with a capital B, and a header that says bearer <token> with a lowercase b returns no token, so the request gets a 401. The HTTP standard treats the scheme as case-insensitive, and a stricter reading would accept both spellings. This helper follows the simple spelling, and a client that sends lowercase bearer is refused. Keep the spelling in mind when a request fails for no visible reason.

The Order of Operations in the Extractor

The extractor runs before the handler body, and inside the extractor the steps run in a fixed order: header first, secret second, verification third, construction last. The order matters, because each step needs the previous one. The header step produces the token, the secret step produces the key material, the verification step needs both, and the construction step needs the verified claims. No step can move earlier than the step that produces its input.

The order also matters for cost. A request with no header fails at the first step, before the secret is read and before any cryptography runs. A request with a bad token fails at the verification step, before the handler body runs. The server does no work for a request it will reject beyond the check that rejects it, and the handler never pays for a request that should have been turned away at the door.

Never Build AuthUser From an Unverified Token:

An AuthUser value must only ever be built from claims that verify_token returned, after the signature and the expiry passed. Building one by decoding the payload by hand, or by copying fields out of a request body, creates a typed user the server never proved, and every handler that takes it would trust a stranger. If a value of this type exists, the token behind it was verified, and that rule is what makes the type worth having.

One subtlety deserves a plain sentence. Extractors run before the handler body, in the order the handler arguments are listed. If a handler takes both AuthUser and a JSON body, the extractor runs first, and a request with a bad token gets the 401 before the body is ever parsed. A request with a good token and a broken body gets the body error instead, because the token check passed and the body parse failed. The 401 always comes first when the token is bad, whatever else is wrong with the request.

A Second Route Sharing the Same Extractor

One extractor serves any number of routes. A settings route needs the same proof as the profile route, and it takes the same argument with no new code in the extractor or in the error file.

src/lib.rs
pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/profile", get(profile))
        .route("/settings", get(settings))
        .with_state(pool)
}
src/handlers.rs
pub async fn settings(user: AuthUser) -> HandlerResult<Json<serde_json::Value>> {
    Ok(Json(json!({ "user_id": user.user_id, "theme": "dark" })))
}

Both routes answer 401 without a token and 200 with one. The extractor lives in one place, so changing how tokens are read or verified touches one implementation. A project that copies the header parsing into every handler ends up with several copies that drift apart, and the drift is where security mistakes hide. The extractor is the single place where the check lives, and the handlers only declare that they need it.

The settings handler also shows why the extractor returns a typed value instead of a bare user id. The handler uses user.user_id to say whose settings these are, and it could use user.role to decide what the user may change. The value carries both pieces, and each handler reads the piece it needs.

A Plain Text Diagram of the Flow

The request passes through the extractor before it reaches the handler, and the two outcomes split at the verification.

request arrives with headers
        |
        v
from_request_parts runs
        |
        v
bearer_token reads the Authorization header
        |
        +-- no token --> AppError::Unauthorized --> 401 + {"error": "unauthorized"}
        |
        v
verify_token checks the signature and expiry
        |
        +-- bad or expired --> AppError::Unauthorized --> 401 + {"error": "unauthorized"}
        |
        v
AuthUser built from the claims
        |
        v
handler body runs with the typed user
        |
        v
200 + {"role": "user", "user_id": 1}

The diagram has no third branch for the secret, because a missing secret fails the same way a bad token does, with the same 401. The extractor collapses every failure into one answer, and the handler only ever sees a verified user.

Testing It

The tests below cover the outcomes the extractor can produce: a good token reaches the handler, and every bad form is refused. They send requests through the router with oneshot, which sends one request directly through the router with no network involved, and they mint their tokens with the same helper the login step uses.

tests/jwt_test.rs
use std::time::{SystemTime, UNIX_EPOCH};

use axum::{
    body::{Body, to_bytes},
    http::{Request, StatusCode},
};
use axum_project::{app, auth::Claims, db::create_pool};
use jsonwebtoken::{EncodingKey, Header, encode};
use tower::ServiceExt;

const SECRET: &str = "test-secret-only-for-local-development";

fn now_secs() -> usize {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs() as usize
}

fn token_with_exp(exp: usize, secret: &str) -> String {
    let claims = Claims {
        sub: 1,
        role: "user".to_string(),
        exp,
    };
    let key = EncodingKey::from_secret(secret.as_bytes()).unwrap();
    encode(&Header::default(), &claims, &key).unwrap()
}

async fn get_profile(token: Option<&str>) -> (StatusCode, String) {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool = create_pool(&database_url).await.unwrap();
    let mut builder = Request::builder().uri("/profile");
    if let Some(token) = token {
        builder = builder.header("authorization", format!("Bearer {token}"));
    }
    let response = app(pool)
        .oneshot(builder.body(Body::empty()).unwrap())
        .await
        .unwrap();
    let status = response.status();
    let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
    (status, String::from_utf8(bytes.to_vec()).unwrap())
}

#[tokio::test]
async fn profile_with_valid_token_returns_user() {
    let token = token_with_exp(now_secs() + 3600, SECRET);
    let (status, body) = get_profile(Some(&token)).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body, r#"{"role":"user","user_id":1}"#);
}

#[tokio::test]
async fn profile_without_token_is_unauthorized() {
    let (status, body) = get_profile(None).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
    assert_eq!(body, r#"{"error":"unauthorized"}"#);
}

#[tokio::test]
async fn profile_with_expired_token_is_unauthorized() {
    let token = token_with_exp(now_secs() - 3600, SECRET);
    let (status, body) = get_profile(Some(&token)).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
    assert_eq!(body, r#"{"error":"unauthorized"}"#);
}

#[tokio::test]
async fn profile_with_wrongly_signed_token_is_unauthorized() {
    let token = token_with_exp(now_secs() + 3600, "a-different-secret");
    let (status, body) = get_profile(Some(&token)).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
    assert_eq!(body, r#"{"error":"unauthorized"}"#);
}

#[tokio::test]
async fn profile_with_tampered_payload_is_unauthorized() {
    let token = token_with_exp(now_secs() + 3600, SECRET);
    let mut parts: Vec<&str> = token.split('.').collect();
    parts[1] = "eyJzdWIiOjIsInJvbGUiOiJhZG1pbiIsImV4cCI6MTc5NDY0ODE1NH0";
    let tampered = parts.join(".");
    let (status, body) = get_profile(Some(&tampered)).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
    assert_eq!(body, r#"{"error":"unauthorized"}"#);
}

The shared get_profile helper builds the request with or without a header, so each test stays short. The expired test uses an expiry an hour in the past, safely outside the 60-second leeway in the default validation, so the result is stable on every run. The tampered test replaces the payload with a forged admin claim and keeps the original signature, which is the exact forgery the signature exists to stop. Run them with:

DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch13_jwt" JWT_SECRET="test-secret-only-for-local-development" cargo test --test jwt_test -- --test-threads=1
test profile_with_expired_token_is_unauthorized ... ok
test profile_with_tampered_payload_is_unauthorized ... ok
test profile_with_valid_token_returns_user ... ok
test profile_with_wrongly_signed_token_is_unauthorized ... ok
test profile_without_token_is_unauthorized ... ok

Common Beginner Mistakes

Reading the header inside the handler

// Wrong - the check belongs in the extractor, not in every handler
pub async fn profile(headers: HeaderMap) -> HandlerResult<Json<serde_json::Value>> {
    let token = bearer_token(&headers).ok_or(AppError::Unauthorized)?;
    let secret = std::env::var("JWT_SECRET").map_err(|_| AppError::Unauthorized)?;
    let claims = verify_token(token, &secret)?;
    Ok(Json(json!({ "user_id": claims.sub, "role": claims.role })))
}

This handler works, and it is the mistake the extractor exists to prevent. Every protected handler would need the same four lines, and the copies would drift apart over time. The fix is the AuthUser argument, which moves the four lines into one implementation and lets the handler start with the verified user. A handler that parses its own headers is a handler that has not yet learned to use an extractor.

Returning the claims instead of a typed user

// Wrong - handlers should receive the identity, not the raw token contents
impl FromRequestParts<PgPool> for Claims {
    type Rejection = AppError;
    async fn from_request_parts(parts: &mut Parts, _state: &PgPool) -> Result<Self, Self::Rejection> {
        let Some(token) = bearer_token(&parts.headers) else {
            return Err(AppError::Unauthorized);
        };
        let secret = std::env::var("JWT_SECRET").map_err(|_| AppError::Unauthorized)?;
        verify_token(token, &secret)
    }
}

Returning Claims directly works, and it is the wrong shape for handlers. The claims carry exp, which no handler needs, and they are named for the token, not for the user. AuthUser carries exactly what handlers need, with names that say what the values are, and it leaves the token details behind. The fix is the two-field struct, which is a deliberate narrowing of the claims into the identity a handler works with.

Forgetting the state type parameter

// Wrong - the state type must match the router state, or Axum cannot use the extractor
impl FromRequestParts for AuthUser {

FromRequestParts takes the state type as a parameter, and leaving it out fails to compile, because the trait is generic over the state. The fix is FromRequestParts<PgPool>, matching the pool the router holds. A router built with a different state type, such as a struct holding the pool and the secret, would need that type here instead. The parameter is part of the contract between the router and the extractor.

Comparing the whole header value to the token

// Wrong - the header value includes the Bearer scheme
let token = parts.headers.get(header::AUTHORIZATION);
match token {
    Some(value) if value.to_str().unwrap() == "expected-token" => Ok(()),
    _ => Err(AppError::Unauthorized),
}

The header value is Bearer <token>, not <token>, so comparing the whole value to the bare token never matches, and every request fails, including the ones with the right token. The fix is the strip_prefix("Bearer ") step in the helper, which removes the scheme before comparing. A related mistake is forgetting the space after Bearer, which leaves a leading space on the token and also never matches.

Verifying the token but ignoring the result

// Wrong - the verification runs, and its answer is thrown away
let _ = verify_token(token, &secret)?;

This line actually does the right thing, because the ? returns early on failure, and the underscore only marks the success value as unused. The real mistake is the version without the ?, where the Result is dropped and the handler carries on with an unverified token. The fix is to keep the ?, or to bind the claims and use them, as the working version does. A verification whose answer is ignored is not a verification at all.

Final Complete Example

Here is everything from this page put together: the claims, the verification helper, the header helper, the extractor, and the two routes that take it.

src/auth.rs
use axum::{
    extract::FromRequestParts,
    http::{HeaderMap, header, request::Parts},
};
use jsonwebtoken::{DecodingKey, Validation, decode};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;

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 verify_token(token: &str, secret: &str) -> Result<Claims, AppError> {
    let key = DecodingKey::from_secret(secret.as_bytes()).map_err(|error| {
        eprintln!("decoding key error: {error}");
        AppError::Unauthorized
    })?;
    let data = decode::<Claims>(token, &key, &Validation::default()).map_err(|error| {
        eprintln!("token decode error: {error}");
        AppError::Unauthorized
    })?;
    Ok(data.claims)
}

pub fn bearer_token(headers: &HeaderMap) -> Option<&str> {
    headers
        .get(header::AUTHORIZATION)
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.strip_prefix("Bearer "))
}

impl FromRequestParts<PgPool> for AuthUser {
    type Rejection = AppError;

    async fn from_request_parts(
        parts: &mut Parts,
        _state: &PgPool,
    ) -> Result<Self, Self::Rejection> {
        let Some(token) = bearer_token(&parts.headers) else {
            return Err(AppError::Unauthorized);
        };
        let secret = std::env::var("JWT_SECRET").map_err(|_| AppError::Unauthorized)?;
        let claims = verify_token(token, &secret)?;
        Ok(AuthUser {
            user_id: claims.sub,
            role: claims.role,
        })
    }
}
src/handlers.rs
use axum::Json;
use serde_json::json;

use crate::{
    auth::AuthUser,
    errors::HandlerResult,
};

pub async fn profile(user: AuthUser) -> HandlerResult<Json<serde_json::Value>> {
    Ok(Json(json!({ "user_id": user.user_id, "role": user.role })))
}

pub async fn settings(user: AuthUser) -> HandlerResult<Json<serde_json::Value>> {
    Ok(Json(json!({ "user_id": user.user_id, "theme": "dark" })))
}
src/lib.rs
pub mod auth;
pub mod db;
pub mod errors;
pub mod handlers;

use axum::{Router, routing::get};
use handlers::{profile, settings};
use sqlx::PgPool;

pub fn app(pool: PgPool) -> Router {
    Router::new()
        .route("/profile", get(profile))
        .route("/settings", get(settings))
        .with_state(pool)
}

Run the checks with these commands:

cargo check
cargo test --test jwt_test
cargo run

Summary

The extractor turns a security check into a function argument, and that move changes where the check lives and who can get it wrong. The check lives in one implementation, the handlers declare their need for it by naming the type, and the compiler enforces the arrangement: a handler that takes AuthUser cannot run without a verified token, because Axum runs the extractor first and refuses the request when it fails. The handler body starts with a typed user it can trust, and it never parses a header, never reads a secret, and never sees a bad token.

The framework to carry forward is the shape of the decision. Whenever a handler needs a value that comes from the request and needs checking, the question is whether the check belongs in the handler or in an extractor. A check that repeats across handlers belongs in an extractor, where it is written once and enforced by the type system, and a check that is specific to one handler stays in that handler. The extractor is the boundary between the raw request and the trusted values a handler works with, and the next step is the header scheme it reads, the exact spelling a client must use to be understood.