route_layer auth
Learn how to apply auth middleware to some routes and not others with route_layer in Axum and why route_layer keeps 404 and 405 responses intact
route_layer is the attachment point that puts auth middleware on some routes and not others. It wraps the routes already in a router, and it runs the middleware only when a request matches one of those routes. A public route stays open, a protected route asks for a token, and a mistyped URL still answers 404 instead of being turned into a failed login.
Where This Fits
The auth middleware from the previous idea knows how to verify a token. That idea attached it to a small protected router and merged that router into the main one, which worked, but it never explained the attachment point itself. This page explains that attachment point. The middleware function is unchanged. What changes is where it is attached, what it covers, and what happens to requests that match nothing.
Think of a building with a public lobby and a locked office floor. The lobby has no badge reader, because anyone may walk in. The office floor has one reader that covers every office on that floor. A visitor who walks into a broom cupboard by mistake does not meet a badge reader. They meet a sign that says the room does not exist. route_layer is the reader on the office floor. It guards the rooms on its floor, and it never answers for rooms that do not exist.
The Smallest Working Version
Create a project with the files below. The error type, the token code, and the middleware are the same as the auth middleware idea, shown in full so this page stands on its own.
[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"] }
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 {
let claims = Claims {
sub: user_id,
role: role.to_string(),
exp: now_seconds() + 3600,
};
let key = EncodingKey::from_secret(jwt_secret().as_bytes()).unwrap();
encode(&Header::default(), &claims, &key).unwrap()
}
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)
}
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.
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("/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 })))
}
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 server and print a token with the same test secret:
JWT_SECRET=test-secret-only-for-local-development cargo run
JWT_SECRET=test-secret-only-for-local-development cargo run --example make_token -- user 7
Four requests show the four behaviours that matter. The public route answers without a token:
curl http://127.0.0.1:3000/public
Anyone can read this.
A 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"}
The same route with a valid token answers 200, replacing TOKEN with the printed value:
curl -H "Authorization: Bearer TOKEN" http://127.0.0.1:3000/me
{"role":"user","user_id":7}
And a path that does not exist answers 404, not 401, even without a token:
curl -i http://127.0.0.1:3000/nope
HTTP/1.1 404 Not Found
content-length: 0
That last answer is the behaviour this whole page is about. The auth middleware never ran for that request. There was no route to protect, so there was nothing for the middleware to do.
Four answers that prove the setup works:
If the public route answers 200 without a token, the protected route answers 401 without one and 200 with one, and the unknown path answers 404 without a token, route_layer is doing its job. The 404 on the unknown path is the result that matters most.
The Same Auth Attached with layer, and the 404 Disappears
Change exactly one thing in the program above. Replace the route_layer call with a layer call on the protected router:
let protected = Router::new()
.route("/me", get(me_handler))
.route("/settings", get(settings_handler))
.layer(middleware::from_fn(auth_middleware));
Everything else stays the same. The middleware function is unchanged, the routes are unchanged, and the good requests behave exactly as before. Only the unknown path changes. GET /nope without a token now returns 401 Unauthorized instead of 404 Not Found.
The reason is the attachment point. The layer method wraps the whole router, including its fallback. The fallback is the answer the router gives when no route matches, which by default is a plain 404. With layer, the auth middleware sits outside the fallback, so every request passes through it first, matched or not. With route_layer, the middleware sits inside the routing decision, so unmatched requests never reach it.
| Request | With route_layer | With layer |
|---|---|---|
GET /me without a token | 401 Unauthorized | 401 Unauthorized |
GET /me with a token | 200 OK | 200 OK |
GET /public without a token | 200 OK | 200 OK |
GET /nope without a token | 404 Not Found | 401 Unauthorized |
The table shows that the two methods agree everywhere except on unmatched paths. That one row is the entire difference, and it is the reason both methods exist. Use layer when a policy genuinely covers everything, including unmatched paths. Logging is the classic case, because the requests that hit a 404 are often the ones worth seeing in the log. Use route_layer when a policy must only apply where a handler would otherwise have run.
A 401 on an unknown path is a bug, not a feature:
When auth is attached with the layer method, every mistyped URL in an API returns 401 instead of 404. Clients debugging a wrong path chase a token problem that does not exist. Attach auth with route_layer so that 404 responses stay 404 responses.
Only Routes Added Before the Call Are Wrapped
route_layer applies to every route that already exists in the router when it is called. It does not apply to only the most recent route, and it does not apply to routes added later. Read the call as "wrap everything so far". This fragment uses the same handlers and middleware from the smallest version:
let app = Router::new()
.route("/me", get(me_handler))
.route_layer(middleware::from_fn(auth_middleware)) // wraps /me only
.route("/public", get(public_handler)); // /public is NOT protected
Here /me requires a token and /public does not, because /public was added after the route_layer call. A request to /me without a token gets a 401. A request to /public without a token gets a 200 with the public text. The program builds without complaint. The router does not warn that /public escaped the layer. That silence is what makes this the most common mistake with route_layer.
The fix is ordering in the code, not a setting. Finish adding routes first, then call route_layer. When a new route is added later, add it above the route_layer call, never below it. Read the router from top to bottom before running it and check that every route the layer should cover sits above the call.
The same ordering rule is why the smallest version on this page builds the protected router separately and merges it. Splitting the routers makes the boundary visible. The protected router contains only the routes that need auth, the route_layer call sits at its end, and the merge joins it to the public routes. A new protected route goes inside the protected router, above the call. A new public route goes on the outer router, where no auth layer can reach it.
A route added after the call escapes the layer silently:
This is a runtime silence, not a compile error. The program builds, the route answers, and the middleware never runs for it. If a protected route suddenly stops asking for a token, check whether it sits below the route_layer call.
Splitting Public and Protected Routers
The merge pattern from the smallest version is worth spelling out, because it is the shape real projects use as they grow. Two routers, two jobs, one merge:
pub fn app() -> Router {
let public = Router::new()
.route("/", get(home_handler))
.route("/public", get(public_handler));
let protected = Router::new()
.route("/me", get(me_handler))
.route("/settings", get(settings_handler))
.route_layer(middleware::from_fn(auth_middleware));
public.merge(protected)
}
async fn home_handler() -> &'static str {
"Welcome. Sign in to see your profile."
}
The public router has no layer at all, so nothing can accidentally protect a route that must stay open, such as a home page or a login page. The protected router has exactly one layer, so nothing can accidentally leave a route unprotected inside it. The merge joins them into a single router for the server. When the project grows a third group, such as admin-only routes, that group becomes a third router with its own layers, merged the same way, and the existing two routers do not change.
A beginner sometimes tries to protect the whole application and then carve out exceptions for public routes. That approach fails, because there is no "except this route" switch on a layer. The merge pattern works the other way around. Each group declares its own protection, and the router table shows at a glance which routes are protected, because the grouping is visible in the code.
One Path, One Method Check, and the 405
route_layer also exists on MethodRouter, which is the value that get(handler) or post(handler) returns. A MethodRouter matches one path, possibly for several methods. Its route_layer runs the middleware only when the path matches and the method is one the router handles. A request with the wrong method keeps its 405 Method Not Allowed instead of being turned into a 401. Here is the complete program, with the same handlers and middleware as the smallest version:
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 {
Router::new().route(
"/me",
get(me_handler).route_layer(middleware::from_fn(auth_middleware)),
)
}
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 Cargo.toml, the error file, the token code, and the entry point are the same as the smallest version. Run it and try three requests:
curl -i http://127.0.0.1:3000/me
curl -H "Authorization: Bearer TOKEN" http://127.0.0.1:3000/me
curl -i -X POST http://127.0.0.1:3000/me
The behaviour is:
GET /mewithout a token returns401 Unauthorized. The path and the method both matched, so the auth middleware ran and refused the request.GET /mewith a token returns200 OKwith the user id and role.POST /mewithout a token returns405 Method Not Allowed, not 401. The path matched but the method did not, so the auth middleware never ran.
Compare that with MethodRouter::layer, which wraps the method router itself. A wrong-method request still passes through that layer on its way to the 405. The two methods look alike and differ exactly here. route_layer is matched-only. layer is per-path. If tests assert a 405 for a wrong method, the middleware on that path needs route_layer.
Three attachment points, one question:
The choice between the router form and the method-router form is always the same question, how wide is the coverage. A group of routes takes the router form. One path takes the method-router form, with layer when wrong-method requests must still pass through, and with route_layer when the 405 must survive. The middleware function itself never changes.
Stacking route_layer Calls
A second route_layer call re-wraps the same routes, and the last call ends up outermost, which means it sees the request first. That order matters as soon as two middlewares depend on each other. Auth and logging are the pair that shows it most clearly. A logging middleware that runs outside auth logs rejected requests too. A logging middleware that runs inside auth only logs requests that passed authentication.
use axum::{extract::Request, middleware::Next, response::Response};
async fn log_requests(request: Request, next: Next) -> Response {
let method = request.method().clone();
let uri = request.uri().clone();
println!("Request: {} {}", method, uri);
let response = next.run(request).await;
println!("Response status: {}", response.status());
response
}
pub fn app() -> Router {
let protected = Router::new()
.route("/me", get(me_handler))
.route_layer(middleware::from_fn(log_requests))
.route_layer(middleware::from_fn(auth_middleware));
Router::new()
.route("/public", get(public_handler))
.merge(protected)
}
The log_requests call comes first, so it is the inner layer. The auth_middleware call comes second, so it is the outer layer. A request meets auth first, then logging, then the handler. A request without a token is refused by auth, and logging never runs for it, so the rejected request leaves no log line. Swap the two calls and the order flips. Logging runs first, the rejected request is logged with its 401 status, and auth runs second. Neither order is wrong in general. The choice depends on whether rejected requests belong in the log, and the calls must be written so the outermost layer is added last.
The same rule covers a second auth-style layer, such as a role check that runs after the token check. The role check must run inside auth, because it reads the AuthUser that auth inserts. The calls are written with the role layer first and the auth layer second, so auth ends up outermost and runs first. Getting that order backwards is a real bug, and it is covered in full on the admin-only route idea, where the two layers are the whole subject.
route_layer Panics on an Empty Router
Calling route_layer before any route has been added is a programming error, and Axum treats it as one. The call panics at runtime with the message "Adding a route_layer before any routes is a no-op. Add the routes you want the layer to apply to first."
// Wrong - panics at runtime, no routes exist yet
let app: Router = Router::new().route_layer(middleware::from_fn(auth_middleware));
The panic is deliberate. A route_layer call with no routes to wrap would silently do nothing, and silent no-ops are how auth ends up missing from a route. If this panic appears, the route_layer call was almost certainly written before the route calls. Move it after them.
route_layer panics, layer does not:
The layer method on an empty router is fine, because it always has something to wrap, the fallback. route_layer on an empty router panics, because with no routes there is nothing for it to wrap. The asymmetry is intentional. A route_layer call with no routes would be a no-op, and silent no-ops are how auth ends up missing.
A Plain Text Diagram of the Flow
The router decides first, and the middleware only runs when the router matched a route.
request arrives
|
v
router: does a route match the path and method?
|
+-- no --> 404 Not Found, or 405 for a wrong method
| (auth middleware never runs)
|
+-- yes --> auth middleware runs
|
+-- token missing or bad --> 401 + {"error": "unauthorized"}
|
+-- token valid --> handler runs --> 200 + the response
The diagram has one decision before the middleware and one inside it. The first decision belongs to the router, and it is the reason route_layer exists. The second decision belongs to the middleware, and it is the same check the auth middleware idea already built. Keeping the two decisions separate is what keeps 404 answers honest.
Testing It
The tests below cover the matrix that defines this page. A public route without a token, a protected route without one, a protected route with one, and an unknown path without one. Each test sends a request through the router with oneshot and checks the status and the exact body.
use axum::{
body::{Body, to_bytes},
http::{Request, StatusCode},
};
use axum_project::{app, auth::token_for};
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, _) = get("/public", None).await;
assert_eq!(status, StatusCode::OK);
}
#[tokio::test]
async fn protected_without_token_is_unauthorized() {
let (status, body) = get("/me", None).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, r#"{"error":"unauthorized"}"#);
let (status, _) = get("/settings", None).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn unknown_path_without_token_is_not_found() {
let (status, _) = get("/nope", None).await;
assert_eq!(status, StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn protected_with_valid_token_is_ok() {
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}"#);
let (status, body) = get("/settings", Some(&token)).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, r#"{"language":"en","theme":"dark"}"#);
}
The unknown-path test is the one that guards this page. If somebody later swaps route_layer for layer, that test fails, because the unknown path starts returning 401 instead of 404. The test makes the attachment point a checked fact instead of a comment in the code.
Run the tests with:
cargo test
Common Beginner Mistakes
Attaching auth with layer and masking every 404
// Wrong - unknown paths return 401 instead of 404
let app = Router::new()
.route("/me", get(me_handler))
.layer(middleware::from_fn(auth_middleware));
This is the mistake the comparison table above exists to prevent. The layer method wraps the fallback, so a mistyped URL is answered as a failed login. The fix is route_layer, which keeps the fallback outside the middleware.
Adding a protected route after the route_layer call
// Wrong - /settings escapes the layer silently
let protected = Router::new()
.route("/me", get(me_handler))
.route_layer(middleware::from_fn(auth_middleware))
.route("/settings", get(settings_handler));
The /settings route answers without a token, and nothing warns about it. The fix is to move the route above the route_layer call, or to build the protected router first and call route_layer once at its end.
Protecting the whole app and breaking the login route
// Wrong - the login route needs no token, but the layer covers it
let app = Router::new()
.route("/login", get(login_handler))
.route("/me", get(me_handler))
.route_layer(middleware::from_fn(auth_middleware));
Both routes sit above the call, so both are wrapped, and a client that has no token yet cannot reach the route that hands tokens out. The fix is the merge pattern. The login route goes on the public router, and only the routes that need a token go in the protected router.
Expecting route_layer to cover the fallback
route_layer cannot cover the fallback, by design. When middleware genuinely must run on unmatched requests, a catch-all logger for example, that is what the layer method is for. The two methods are complements, not substitutes, and choosing between them is the question of whether an unmatched request should pass through the middleware at all.
Confusing MethodRouter route_layer with MethodRouter layer
// Wrong for a 405 test - layer lets the middleware run on a wrong method
get(me_handler).layer(middleware::from_fn(auth_middleware))
A POST to a GET-only route passes through that layer on its way to the 405, so a missing token turns the answer into a 401. The fix is route_layer on the method router, which runs only when the path and the method both match.
Calling route_layer on an empty router
// Wrong - panics at runtime
let app: Router = Router::new().route_layer(middleware::from_fn(auth_middleware));
There is nothing to wrap, so Axum panics rather than silently doing nothing. The fix is to add the routes first and call route_layer after them.
Final Complete Example
Here is the full project from this page, with the error type, the token code, the middleware, a public router and a protected router merged together, 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 {
let claims = Claims {
sub: user_id,
role: role.to_string(),
exp: now_seconds() + 3600,
};
let key = EncodingKey::from_secret(jwt_secret().as_bytes()).unwrap();
encode(&Header::default(), &claims, &key).unwrap()
}
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 public = Router::new()
.route("/", get(home_handler))
.route("/public", get(public_handler));
let protected = Router::new()
.route("/me", get(me_handler))
.route("/settings", get(settings_handler))
.route_layer(middleware::from_fn(auth_middleware));
public.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 decision framework for this page is a single question asked about every middleware, must an unmatched request pass through it? Auth answers no, because a refusal must never rewrite the answer to "does this path exist". Logging answers yes, because the requests that hit a 404 are often the ones worth seeing. That one answer picks the attachment point. A no takes a route_layer form, so the middleware runs only when a route matched. A yes takes a layer form, so it wraps the fallback too.
The second decision is how wide the coverage is. A group of routes takes the router form, with the routes added first and the call at the end, or split into a protected router that is merged in. One path takes the method-router form, with route_layer when the 405 must survive. Everything else on this page, the ordering rule, the panic on an empty router, the stacking order, is a consequence of that matched-only condition. Once the condition is clear, the method chooses itself, and the auth check from the previous idea slots into place without changing a line.