Unopinionated Axum stance
Learn what Axum does and does not provide for auth, and why the framework leaves login session and token choices to your app
Axum ships no built-in login, no built-in session system, and no built-in token system. There is no axum::auth module, no login handler to call, and no user model to fill in. What Axum does ship is the machinery auth is built from: routers that map paths to handlers, extractors that pull data out of requests, middleware that can run a check before a handler, and state that can hold configuration the whole app shares. The app picks its own auth crates and writes its own checks on top of those pieces.
Where This Fits
The three approaches before this page all answer the same question differently: the server remembers the login, the client carries a token, or the token carries its own proof. Each approach needs code that checks credentials, stores something, and refuses requests that fail the check. This page answers the question underneath all three: which of that code does Axum write for you, and which of it do you write yourself? The answer is that Axum writes the plumbing and you write the auth.
Think of it like a kitchen that sells knives, pans, and a stove, but no finished meals. The tools are good, and every meal in the restaurant is made with them, but the menu is yours. Axum is the kitchen. The login flow is the meal.
The Smallest Working Version
Here is the smallest protected route you can build with Axum alone. A middleware function checks the Authorization header before the handler runs, and a route without the middleware stays open to everyone. Nothing in this code comes from an auth crate. Every piece is Axum or its Tower foundation: a Router, a middleware function, a Next that passes the request on, and an error type the app defines itself.
use axum::{
Json, Router,
http::{HeaderMap, StatusCode, header},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::get,
};
use serde_json::json;
pub enum AppError {
Unauthorized,
Forbidden,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match self {
AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized"),
AppError::Forbidden => (StatusCode::FORBIDDEN, "forbidden"),
};
(status, Json(json!({ "error": message }))).into_response()
}
}
pub fn app() -> Router {
Router::new()
.route("/profile", get(profile))
.route_layer(middleware::from_fn(check_token))
.route("/public", get(|| async { "Anyone can read this." }))
}
async fn check_token(headers: HeaderMap, request: axum::extract::Request, next: Next) -> Response {
let token = headers
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
.unwrap_or("");
if token != "demo-token" {
return AppError::Unauthorized.into_response();
}
next.run(request).await
}
async fn profile() -> Json<serde_json::Value> {
Json(json!({ "id": 1, "name": "Ada", "email": "ada@example.com" }))
}
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!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The Cargo.toml file needs these dependencies:
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde_json = "1"
Run it with cargo run, then try the protected route with and without the token:
curl -i http://127.0.0.1:3000/profile
curl -i http://127.0.0.1:3000/profile -H "Authorization: Bearer demo-token"
curl http://127.0.0.1:3000/public
The first request answers 401 with a JSON body:
HTTP/1.1 401 Unauthorized
{"error":"unauthorized"}
The second answers 200 with the profile, and the third answers 200 with no token at all, because /public sits outside the middleware. The error body is always the same shape, {"error": "..."}, which is the shape the AppError type produces for every error in the app: Unauthorized becomes 401 with "unauthorized", and Forbidden becomes 403 with "forbidden".
Working Setup:
If the profile request without a token returns 401 with {"error":"unauthorized"}, the same request with Bearer demo-token returns Ada, and the public route works with no token, the guard is in place and the open route is still open.
How the Guard Works
The guard is a middleware function, which is a function that runs before the handler and decides whether the request continues. middleware::from_fn turns an ordinary async function into middleware Axum can attach to routes. The function takes three arguments. headers is a HeaderMap, the collection of headers on the incoming request. request is the request itself. next is the handle to the rest of the pipeline, the handler and anything after it.
The function reads the Authorization header, strips the Bearer prefix, and compares the rest with the expected token. If the token does not match, it returns the Unauthorized error at once, and the handler never runs. If the token matches, it calls next.run(request).await, which hands the request on to the handler and returns the handler's response.
The route_layer call decides which routes the guard covers. It applies to the routes added before it in the builder chain, which is only /profile here. /public is added after the route_layer call, so it is outside the guard. Order in the builder chain is the scope: routes above the layer are guarded, routes below it are not. That ordering is the whole mechanism for protecting some routes and leaving others open.
The AppError type is app code, not Axum code. Axum does not define how errors look. The app defines an enum with the cases it needs, implements IntoResponse for it, and every handler can return it. Unauthorized maps to 401 with "unauthorized" and Forbidden maps to 403 with "forbidden", and the body is always {"error": "..."}. One type, one shape, every error in the app.
What Axum Provides
Axum provides the pieces that every auth design needs, and it provides them as general tools, not as auth features. The Router maps paths and methods to handlers, so a login route and a protected route are ordinary routes. Handlers are async functions, so a login handler is an ordinary handler that reads JSON and returns JSON. Extractors pull data out of requests: State shares configuration across handlers, HeaderMap reads headers, and Json reads the body. Middleware runs a check before a handler, and Next passes the request on when the check succeeds.
Axum also provides the response tools. A handler can return a status code, a header map, and a JSON body together, which is how login answers with a token or a cookie. The IntoResponse trait turns an app error type into an HTTP response, which is how the whole app answers auth failures in one consistent shape.
None of these pieces knows anything about auth. State holds any data, not just auth configuration. HeaderMap reads any header, not just Authorization. Middleware can check anything, not just tokens. That generality is deliberate. Axum is built on the Tower ecosystem, and its own documentation says it has no middleware system of its own: it uses Tower's Service trait, and gets timeouts, tracing, compression, and the rest from Tower layers. Auth is one more thing built on that same foundation, not a special case inside the framework.
What Axum Does Not Provide
Axum provides no login. There is no handler that checks a password, no function that creates a session, and no helper that issues a token. The login handler in the earlier approaches, with its password check and its token creation, is app code from the first line to the last.
Axum provides no session store. There is no table of sessions, no cookie manager, and no logout helper. The session map, the cookie flags, and the expiry check are all app code. A crate like tower-sessions can supply the session machinery, but that crate is a separate choice the app makes, not something Axum ships.
Axum provides no token verification. There is no function that decodes a JWT, no key handling, and no expiry check. The token map, the signature check, and the claims struct are all app code or code from a crate the app picks, such as jsonwebtoken. Axum does not know what a token is.
Axum provides no user model and no password handling. There is no User struct, no password hashing, and no users table in the framework. The User struct with id, name, and email comes from the app's own users table, and password hashing comes from a crate the app picks. Axum never sees a password.
State Is Not for Per-Request Auth Data:
Router state is shared across all requests, and Axum's own documentation says it is not suitable for holding data derived from a request, such as authorisation data extracted in middleware. A token read from one request must never be put in State, where the next request could read it. Configuration that is the same for every request, like the expected token in the richer example, belongs in state. Facts about one request belong to that request, and they travel with it through the handler arguments or the request extensions.
Why Axum Leaves Auth Out
Three reasons explain the choice. First, apps disagree about auth. A browser app wants sessions and cookies. A public API wants tokens and headers. An internal service wants mutual TLS or a shared secret. A framework that picked one would fight the other two. A framework that picks none lets each app choose the design that fits its clients.
Second, auth crates already exist and improve on their own schedule. Password hashing, session storage, and JWT handling each have crates maintained by people who specialise in them. If Axum bundled its own versions, those versions would age with the framework release cycle instead of their own. By staying out, Axum lets the app upgrade its auth crates without upgrading the framework, and lets the framework upgrade without touching auth.
Third, keeping auth out keeps Axum small and honest about what it is. Axum is a routing and request-handling library. Its job is to get a request to the right handler with the right data, and to turn the handler's answer into a response. Auth is a policy the app sets on top of that job: which requests may reach which handlers, and what proof they must show. The policy changes from app to app. The plumbing does not.
A Richer Example With Config in State and a 403 Route
The smallest version hard-codes the expected token inside the guard function, which is fine for a demo and wrong for a real app. This richer version moves the expected token into shared state with middleware::from_fn_with_state, and adds an /admin route that returns Forbidden, showing the other half of the AppError type in action. The admin handler always refuses here, because this small example has no role data yet; its job is to show the 403 shape, not to enforce a real role.
use axum::{
Json, Router,
extract::State,
http::{HeaderMap, StatusCode, header},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::get,
};
use serde_json::json;
#[derive(Clone)]
struct AuthConfig {
expected_token: String,
}
pub enum AppError {
Unauthorized,
Forbidden,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match self {
AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized"),
AppError::Forbidden => (StatusCode::FORBIDDEN, "forbidden"),
};
(status, Json(json!({ "error": message }))).into_response()
}
}
#[tokio::main]
async fn main() {
let config = AuthConfig {
expected_token: "demo-token".to_string(),
};
let app = Router::new()
.route("/profile", get(profile))
.route("/admin", get(admin))
.route_layer(middleware::from_fn_with_state(config.clone(), check_token))
.route("/public", get(|| async { "Anyone can read this." }))
.with_state(config);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
async fn check_token(
State(config): State<AuthConfig>,
headers: HeaderMap,
request: axum::extract::Request,
next: Next,
) -> Response {
let token = headers
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
.unwrap_or("");
if token != config.expected_token {
return AppError::Unauthorized.into_response();
}
next.run(request).await
}
async fn profile() -> Json<serde_json::Value> {
Json(json!({ "id": 1, "name": "Ada", "email": "ada@example.com" }))
}
async fn admin() -> Result<Json<serde_json::Value>, AppError> {
Err(AppError::Forbidden)
}
Two changes carry the new behaviour. The guard now takes a State<AuthConfig> argument, and from_fn_with_state supplies it. The token lives in one place, the config, instead of inside the guard function, so changing it means editing one value. In a real app that value comes from an environment variable or a config file, not from source code, and the shape stays the same: the guard reads config, the config comes from outside the code.
The admin route shows the difference between 401 and 403 in one pair of requests. The profile request with the right token succeeds. The admin request with the same right token returns 403 with {"error":"forbidden"}. The server knows who is asking in both cases: the token passed the guard. The difference is that the admin route refuses this user anyway. The retry test makes the meaning concrete: if logging in again could fix the request, the answer is 401; if logging in again changes nothing, the answer is 403. Here logging in again changes nothing, so 403 is right.
curl -i http://127.0.0.1:3000/profile -H "Authorization: Bearer demo-token"
curl -i http://127.0.0.1:3000/admin -H "Authorization: Bearer demo-token"
HTTP/1.1 200 OK
{"id":1,"name":"Ada","email":"ada@example.com"}
HTTP/1.1 403 Forbidden
{"error":"forbidden"}
Three Places to Put the Check
Axum gives three places for an auth check, and the choice is about scope, not about power. The first is middleware on a group of routes, which is what this page uses. One guard covers every route above the route_layer call, so a new protected route gets the check by being added above the layer. This is the right place when several routes share one rule.
The second is a check inside a single handler. A handler that reads the header itself and returns Unauthorized when the token is wrong needs no middleware at all. This is the right place when one route has a rule no other route shares, or when the check needs data only that handler has. The cost is repetition: every handler that needs the same check must repeat it, and a forgotten repeat is an open route.
The third is an extractor, a type that pulls the authenticated user out of the request before the handler runs, and refuses the request when the proof is missing. The handler then takes the user as an argument and never sees the token at all. This is the right place when handlers want the user, not the proof: the check and the user lookup happen once, in one place, and every handler gets a typed user. The extractor is the shape the later auth pages build on, and it is built from the same Axum pieces as the middleware: FromRequestParts, headers, and state.
None of the three is an Axum auth feature. All three are Axum tools pointed at an auth problem. Picking between them is picking where the check lives, not picking a different framework.
Middleware, Extractors, and State Are General Tools:
Every piece on this page is a general Axum tool with uses far beyond auth. Middleware logs requests, adds headers, and enforces timeouts. Extractors read paths, queries, and bodies. State shares database pools and configuration. Auth is one job these tools do, not the job they were built for, and that is why none of them mentions users, logins, or tokens.
What Happens When a Request Arrives
The full path of a request through the guard, from the socket to the handler, looks like this:
Client sends request with Authorization header
|
v
Router matches the path and method
|
v
route_layer middleware runs check_token
|
v
Token missing or wrong -> 401, handler never runs
|
v
Token matches -> next.run(request) passes it on
|
v
Handler runs and returns the response
|
v
Client receives the response
The middleware sits between the router and the handler. It sees the request before the handler does, and it can stop the request there. A request that fails the check never reaches the handler, which means the handler code can assume the check already passed. That assumption is the point of putting the check in middleware: the handler stays focused on its own job, and the guard stays focused on the proof.
Testing the Guard
A test can drive the guard without a network connection, using tower::ServiceExt and its oneshot method, which sends one mock request straight through the Router. Three cases pin the guard down: no token means 401 with the JSON error body, the right token means 200, and the public route means 200 with no token at all.
use axum::{
body::Body,
http::{Request, StatusCode, header},
};
use axum_project::app;
use tower::ServiceExt;
#[tokio::test]
async fn profile_without_token_is_401_json_error() {
let response = app()
.oneshot(
Request::builder()
.uri("/profile")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(value["error"], "unauthorized");
}
#[tokio::test]
async fn profile_with_demo_token_is_ok_and_public_is_open() {
let app = app();
let profile = app
.clone()
.oneshot(
Request::builder()
.uri("/profile")
.header(header::AUTHORIZATION, "Bearer demo-token")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(profile.status(), StatusCode::OK);
let public = app
.oneshot(
Request::builder()
.uri("/public")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(public.status(), StatusCode::OK);
}
The tower crate is needed as a dev dependency:
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Run the tests with cargo test. The first test fails if the guard stops refusing requests without a token, or if the error body stops being {"error":"unauthorized"}. The second test fails if a good token stops working, or if the public route accidentally falls under the guard. Together they pin the exact contract of this page: the guard protects its routes, the open route stays open, and failures speak in the app's one error shape.
Common Beginner Mistakes
Looking for an Auth Module That Does Not Exist
// Wrong - Axum has no auth module, this import does not exist
use axum::auth::login;
Axum's crate root holds routing, handling, extraction, middleware, and response types. It holds no login, no session, and no token type. The compiler rejects the import, and the fix is to stop looking for it: the login handler is app code, the token check is app code, and the crates that help with them are picked by the app, not by the framework.
Storing Request Auth Data in Router State
// Wrong - state is shared across requests, one user's token leaks into another's
async fn check_token(State(state): State<AppState>, ...) {
state.current_token = token;
}
Router state is one value shared by every request the app serves. Writing a token from one request into state means the next request, from a different user, can read it. Axum's own documentation says state is not suitable for data derived from a request, such as authorisation data, and points to Extension instead. The fix is to keep per-request facts on the request itself, and keep only app-wide configuration in state.
Repeating the Check in Every Handler
// Wrong - the same five lines in ten handlers, and one handler will forget them
async fn profile(headers: HeaderMap) -> ... { check(headers)?; ... }
async fn settings(headers: HeaderMap) -> ... { check(headers)?; ... }
A check copied into every handler is a check that will be forgotten in exactly one handler, and that handler becomes the open door. The fix is to put the shared check in one place, middleware over the routes it covers, and let the handlers assume it already ran. A handler keeps its own check only when its rule is genuinely its own.
Returning 403 When the Server Does Not Know Who Is Asking
// Wrong - no token was presented, so the server cannot know who is asking
if token.is_empty() {
return AppError::Forbidden.into_response();
}
A missing token means the server does not know who is asking, and that is 401. A 403 means the server knows who is asking and refuses anyway, like the admin route in the richer example. The retry test settles it: if logging in again could fix the request, the answer is 401. A request with no token at all can be fixed by logging in, so it is 401, never 403.
A Guard That Never Runs Is No Guard:
A middleware attached with route_layer covers only the routes added before it in the builder chain. A protected route added after the layer call is open to everyone, and nothing warns about it. When a route must be protected, add it above the layer call, and write a test that requests it without a token and expects 401.
Final Complete Example
Here is everything from this page in one place: the guard middleware with its token in config, the protected routes, the open route, the admin route that answers 403, and the app error type that gives every failure the same shape.
use axum::{
Json, Router,
extract::State,
http::{HeaderMap, StatusCode, header},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::get,
};
use serde_json::json;
#[derive(Clone)]
struct AuthConfig {
expected_token: String,
}
pub enum AppError {
Unauthorized,
Forbidden,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match self {
AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized"),
AppError::Forbidden => (StatusCode::FORBIDDEN, "forbidden"),
};
(status, Json(json!({ "error": message }))).into_response()
}
}
#[tokio::main]
async fn main() {
let config = AuthConfig {
expected_token: "demo-token".to_string(),
};
let app = Router::new()
.route("/profile", get(profile))
.route("/admin", get(admin))
.route_layer(middleware::from_fn_with_state(config.clone(), check_token))
.route("/public", get(|| async { "Anyone can read this." }))
.with_state(config);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
async fn check_token(
State(config): State<AuthConfig>,
headers: HeaderMap,
request: axum::extract::Request,
next: Next,
) -> Response {
let token = headers
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
.unwrap_or("");
if token != config.expected_token {
return AppError::Unauthorized.into_response();
}
next.run(request).await
}
async fn profile() -> Json<serde_json::Value> {
Json(json!({ "id": 1, "name": "Ada", "email": "ada@example.com" }))
}
async fn admin() -> Result<Json<serde_json::Value>, AppError> {
Err(AppError::Forbidden)
}
# Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde_json = "1"
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Run it with cargo run and drive it with the curl commands from the richer example: profile without a token gives 401, profile with the token gives Ada, admin with the token gives 403, and the public route works with nothing at all.
Summary
The decision Axum makes is to supply the tools and refuse the policy, and that refusal is the framework's most useful feature. Routers, extractors, middleware, and state are general pieces that serve logging, timeouts, and compression as well as auth, and none of them knows what a user is. The app brings the policy: which approach fits its clients, which crates supply the pieces it will not write itself, and where the one check lives so that no route is protected by accident. The mental model to keep is the kitchen: Axum sells the knives and the stove, and the meal is yours to cook.
That model is also the rule for everything that follows. When a later page reaches for a crate, it is not filling a gap Axum forgot. It is using the freedom Axum deliberately left open, and the test of any such crate is whether it fits the app's clients and its policy. Pick the approach first, pick the crate second, and let the framework stay out of both decisions.