Admin-only route
Learn how to build an Axum admin-only route that returns 401 when the token is missing or bad and 403 when the user is known but not an admin
An admin-only route is a route that two gates guard instead of one. The first gate checks identity, and it answers 401 when the token is missing or bad. The second gate checks the role, and it answers 403 when the user is known but not an admin. Only a request that passes both gates reaches the handler.
Where This Fits
The auth middleware already answers the identity question. It verifies the token and attaches the user to the request. What it does not answer is whether that user may do this particular thing. A signed-in ordinary user asking for the admin area is known to the server, and the server still says no, because knowing who someone is does not mean they may do everything. This page adds the second gate, a small middleware that reads the role the first gate attached and refuses everyone who is not an admin.
Think of a company office. The badge reader at the entrance checks whether you work here. That is the 401 check. The locked door to the server room checks whether your badge opens that particular door. You work here, your badge is real, and the door still stays shut, because your job does not include the server room. That is the 403 answer. The two checks happen in order, at two different doors, and neither one can do the other's job.
The Smallest Working Version
Create a project with the files below. The error type, the token code, and the auth middleware are the same as the auth middleware idea, shown in full so this page stands on its own. The new piece is require_admin, a second middleware that reads the role.
[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>;
Both new answers on this page come from this file. Unauthorized maps to 401 with the body {"error":"unauthorized"}, and Forbidden maps to 403 with the body {"error":"forbidden"}. The two bodies look alike on purpose. The status code tells them apart.
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 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 async fn require_admin(
request: Request,
next: Next,
) -> Result<Response, AppError> {
let role = request
.extensions()
.get::<AuthUser>()
.map(|user| user.role.clone());
match role.as_deref() {
None => Err(AppError::Unauthorized),
Some("admin") => Ok(next.run(request).await),
Some(_) => Err(AppError::Forbidden),
}
}
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.
require_admin is the second gate, and it is deliberately small. It reads the AuthUser from the request extensions, which is where the auth middleware put it. Three cases follow. When no user is attached, the answer is 401, because the identity is unknown, and that case should not happen when the layers are stacked correctly, but the function answers it safely instead of panicking. When the role is exactly "admin", the request passes on to the handler. When the role is anything else, the answer is 403.
pub mod auth;
pub mod errors;
use axum::{
Json, Router,
extract::Extension,
middleware,
routing::get,
};
use serde_json::json;
use auth::{AuthUser, auth_middleware, require_admin};
use errors::AppError;
pub fn app() -> Router {
let user_routes = Router::new()
.route("/me", get(me_handler))
.route_layer(middleware::from_fn(auth_middleware));
let admin_routes = Router::new()
.route("/admin", get(admin_handler))
.route_layer(middleware::from_fn(require_admin))
.route_layer(middleware::from_fn(auth_middleware));
Router::new()
.route("/public", get(public_handler))
.merge(user_routes)
.merge(admin_routes)
}
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 admin_handler(
Extension(user): Extension<AuthUser>,
) -> Json<serde_json::Value> {
Json(json!({ "message": format!("Welcome to the admin area, user {}.", user.user_id) }))
}
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 two tokens, one for an ordinary user and one for an admin, 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
JWT_SECRET=test-secret-only-for-local-development cargo run --example make_token -- admin 1
Five requests show the five outcomes. The public route answers without a token:
curl http://127.0.0.1:3000/public
Anyone can read this.
The admin route without a token answers 401:
curl -i http://127.0.0.1:3000/admin
HTTP/1.1 401 Unauthorized
content-type: application/json
content-length: 24
{"error":"unauthorized"}
With a bad token the answer is the same 401:
curl -i -H "Authorization: Bearer this.is.not.a.token" http://127.0.0.1:3000/admin
HTTP/1.1 401 Unauthorized
content-type: application/json
content-length: 24
{"error":"unauthorized"}
With a valid ordinary user token the answer is 403, replacing USER_TOKEN with the printed user token:
curl -i -H "Authorization: Bearer USER_TOKEN" http://127.0.0.1:3000/admin
HTTP/1.1 403 Forbidden
content-type: application/json
content-length: 21
{"error":"forbidden"}
With a valid admin token the handler answers, replacing ADMIN_TOKEN with the printed admin token:
curl -H "Authorization: Bearer ADMIN_TOKEN" http://127.0.0.1:3000/admin
{"message":"Welcome to the admin area, user 1."}
Working Setup:
If no token gives 401, a bad token gives 401, the ordinary user token gives 403, and the admin token gives 200 with the welcome message, both gates are wired up correctly. The 403 in the middle is the result that proves the second gate exists. Without it, the user token would either be refused as unknown or let straight through.
Why Two Gates Instead of One
One middleware could do both jobs. It could verify the token, read the role, and refuse non-admins in a single function. That version is shorter, and for a project with exactly one admin route it would work. It stops working well as soon as a second kind of route appears, because the combined function can only answer one question. A route that any signed-in user may reach needs the identity check without the role check, and a route that only admins may reach needs both. Two small functions compose. One combined function has to be copied and changed for each combination, and the copies drift apart.
The split also keeps each function honest about what it knows. The auth middleware knows about tokens, secrets, signatures, and expiry, and nothing about roles. The admin middleware knows about one string, "admin", and nothing about tokens. When the token scheme changes, only the first function changes. When a new role appears, only the second function changes, plus the routes that use it.
Understanding require_admin Line by Line
The function is short, and each of its lines answers one question about the request.
Reading the user from the extensions
let role = request
.extensions()
.get::<AuthUser>()
.map(|user| user.role.clone());
request.extensions() gives read access to the storage area where the auth middleware inserted the AuthUser. The .get::<AuthUser>() call looks up a value of exactly that type, and returns an Option, a value that is either present or absent. The .map(|user| user.role.clone()) call turns the user into just its role string, still wrapped in an Option. The role is cloned into a new String here, because the request is about to move into next.run, and a borrowed role could not outlive that move. Cloning one short string per request costs almost nothing, and it keeps the borrow checker satisfied.
Sorting the three cases
match role.as_deref() {
None => Err(AppError::Unauthorized),
Some("admin") => Ok(next.run(request).await),
Some(_) => Err(AppError::Forbidden),
}
The match sorts the role into three cases. None means no user was attached, so the identity is unknown, and the answer is 401. Some("admin") means the user is an admin, so the request passes on to the handler. Some(_) means the user is known and is not an admin, so the answer is 403. The as_deref() call turns the Option<String> into an Option<&str>, so the arms can match against string literals instead of owned strings.
The order of the arms is the design. Identity is checked before permission, because permission has no meaning without an identity to attach it to. A function that checked permission first would have to answer the question "may this unknown user do this", which has no sensible answer.
The role check trusts the middleware, not the client:
The require_admin function never reads the token. It reads the AuthUser that the auth middleware built from verified claims. A client cannot smuggle a role past it by editing the token, because editing the token breaks the signature, and the auth middleware refuses the request before require_admin ever runs.
The Stacking Order, and Why It Is Backwards
The two route_layer calls on the admin router are written in an order that looks backwards at first glance:
let admin_routes = Router::new()
.route("/admin", get(admin_handler))
.route_layer(middleware::from_fn(require_admin))
.route_layer(middleware::from_fn(auth_middleware));
The require_admin call comes first, and the auth_middleware call comes second. A second route_layer call re-wraps the same routes, and the last call ends up outermost, which means it sees the request first. So auth, added last, is outermost, and it runs first. It verifies the token and inserts the user. Then require_admin, added first and sitting inside, runs second, and finds the user waiting in the extensions. Then the handler runs.
Swap the two calls and the whole thing breaks:
// Wrong - require_admin runs before auth_middleware
let admin_routes = Router::new()
.route("/admin", get(admin_handler))
.route_layer(middleware::from_fn(auth_middleware))
.route_layer(middleware::from_fn(require_admin));
Now require_admin is outermost and runs first, before any user has been attached. It finds nothing in the extensions, and every request gets a 401, including the ones with a valid admin token. The program builds, the routes answer, and the admin area is locked to everyone. The fix is the order shown in the working version. When two middlewares depend on each other, the one that produces the data is added last, so it runs first.
A useful way to read a stack of route_layer calls is from the bottom up. The last call is the first gate a request meets. The first call is the last gate before the handler. Write the calls in that order, producer last, consumer first, and the request flows through them in the order the data needs.
401 and 403 Side by Side
The two statuses are easy to confuse because both say no, and the difference only shows up when the request is examined closely. The table below puts the questions, the causes, and the right client reaction next to each other.
| 401 Unauthorized | 403 Forbidden | |
|---|---|---|
| Question asked | Who is asking? | May this user do this? |
| State of the request | No usable identity | Identity known, permission missing |
| Cause | Missing, expired, or wrong credentials | Authenticated user lacks the admin role |
| Logging in again helps | Yes, with valid credentials | No, the same user gets the same answer |
| What changes the answer | Valid credentials | A different user, or a permission change |
The retry test decides between them in one sentence. If logging in again could fix the request, the answer is 401. If logging in again changes nothing, the answer is 403. Every example on this page follows that test. A request with no token gets 401, because there is nothing to check permission against. A request with a token for an ordinary user, asking for the admin route, gets 403, because the user is known and the rule is about the role. A request with an admin token asking for a route that does not exist gets 404, because permission passed and the data is missing.
One status per question:
Each status answers one question. 401 answers identity, 403 answers permission, 404 answers existence, 422 answers input. A handler that returns a status for the wrong question sends the client down the wrong path. Check which question failed before choosing the variant.
A Richer Complete Example
One admin route shows the gates. A realistic admin area has several, and the same two layers cover all of them without any new check code. Add a second admin route to the admin router, and a settings route for ordinary signed-in users to the user 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, require_admin};
use errors::AppError;
pub fn app() -> Router {
let user_routes = Router::new()
.route("/me", get(me_handler))
.route("/settings", get(settings_handler))
.route_layer(middleware::from_fn(auth_middleware));
let admin_routes = Router::new()
.route("/admin", get(admin_handler))
.route("/admin/report", get(admin_report_handler))
.route_layer(middleware::from_fn(require_admin))
.route_layer(middleware::from_fn(auth_middleware));
Router::new()
.route("/public", get(public_handler))
.merge(user_routes)
.merge(admin_routes)
}
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" }))
}
async fn admin_handler(
Extension(user): Extension<AuthUser>,
) -> Json<serde_json::Value> {
Json(json!({ "message": format!("Welcome to the admin area, user {}.", user.user_id) }))
}
async fn admin_report_handler() -> Json<serde_json::Value> {
Json(json!({ "report": "weekly totals", "signups": 42 }))
}
The /admin/report route needs no new middleware, because it sits in the admin router, above both route_layer calls. An ordinary user token gets 403 on it, exactly as on /admin, and an admin token gets the report. The /settings route sits in the user router, which carries only the auth layer, so an ordinary user token reaches it fine. The grouping is the protection. A route is admin-only because it lives in the admin router, not because its handler remembers to check.
Try the report route with both tokens:
curl -H "Authorization: Bearer USER_TOKEN" http://127.0.0.1:3000/admin/report
{"error":"forbidden"}
curl -H "Authorization: Bearer ADMIN_TOKEN" http://127.0.0.1:3000/admin/report
{"report":"weekly totals","signups":42}
Variations on the Role Check
The two-layer shape is the default, and the variations below change one decision each while keeping the two gates in order.
Checking the role inside the handler
When exactly one route needs the role check, and no other route will ever need it, the check can live in the handler instead of in a second middleware. The handler reads the AuthUser with the Extension extractor and refuses non-admins itself:
async fn admin_handler(
Extension(user): Extension<AuthUser>,
) -> Result<Json<serde_json::Value>, AppError> {
if user.role != "admin" {
return Err(AppError::Forbidden);
}
Ok(Json(json!({
"message": format!("Welcome to the admin area, user {}.", user.user_id)
})))
}
The route then needs only the auth layer, because the handler does the role check. This shape is fine for one route, and it is the shape the error pages used. It becomes a liability at two routes, because the check is now copied into every admin handler, and a handler written in a hurry can forget it. Use the middleware shape when more than one route needs the rule, and use the handler shape only when the rule genuinely belongs to a single route.
One middleware that takes the required role
When several roles exist, one middleware per role multiplies fast. A single middleware that takes the required role as state covers them all. The function takes the role through State, and the layer is built with the role attached:
use axum::extract::State;
pub async fn require_role(
State(required): State<String>,
request: Request,
next: Next,
) -> Result<Response, AppError> {
let role = request
.extensions()
.get::<AuthUser>()
.map(|user| user.role.clone());
match role.as_deref() {
None => Err(AppError::Unauthorized),
Some(role) if role == required => Ok(next.run(request).await),
Some(_) => Err(AppError::Forbidden),
}
}
Attach it with from_fn_with_state, passing the role at the point where the layer is built:
let admin_routes = Router::new()
.route("/admin", get(admin_handler))
.route_layer(middleware::from_fn_with_state(
"admin".to_string(),
require_role,
))
.route_layer(middleware::from_fn(auth_middleware));
The same function protects a route for any role, because the role is a value passed in, not a string baked into the function. A route for editors would pass "editor" instead. The stacking order stays the same. The role layer is added first, the auth layer second, so auth runs first and the role layer finds the user waiting.
Returning 403 from the handler for a missing resource
Some applications return 404 instead of 403 when a resource is hidden from a user, so that the user cannot tell whether it exists. That is a deliberate design choice, and it uses 404, not 403, as the hiding status. Returning 403 for a resource that simply does not exist confuses the client. It says the user lacks permission for something that is not there at all. A missing resource is a 404, whatever the user may do elsewhere.
A Plain Text Diagram of the Flow
The request passes two gates in order, and the failure at each gate has its own status.
request arrives with Authorization header
|
v
auth_middleware: is the token valid?
|
+-- no --> AppError::Unauthorized --> 401 + {"error": "unauthorized"}
|
+-- yes --> insert AuthUser, then require_admin runs
|
+-- role is "admin" --> handler builds the response
| |
| v
| 200 + {"message": "Welcome ..."}
|
+-- role is anything else --> AppError::Forbidden
|
v
403 + {"error": "forbidden"}
The diagram has no branch where the role is checked before the token, because that branch has no sensible answer. Identity first, permission second, handler third. That order is the whole design.
Testing It
The tests cover the full matrix, no token, bad token, ordinary user token, and admin token, for the admin route, plus the ordinary route to prove the user token still works where it should. 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 admin_without_token_is_unauthorized() {
let (status, body) = get("/admin", None).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, r#"{"error":"unauthorized"}"#);
}
#[tokio::test]
async fn admin_with_bad_token_is_unauthorized() {
let (status, body) = get("/admin", Some("bad.token.here")).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert_eq!(body, r#"{"error":"unauthorized"}"#);
}
#[tokio::test]
async fn admin_with_user_token_is_forbidden() {
let token = token_for(7, "user");
let (status, body) = get("/admin", Some(&token)).await;
assert_eq!(status, StatusCode::FORBIDDEN);
assert_eq!(body, r#"{"error":"forbidden"}"#);
}
#[tokio::test]
async fn admin_with_admin_token_returns_welcome() {
let token = token_for(1, "admin");
let (status, body) = get("/admin", Some(&token)).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, r#"{"message":"Welcome to the admin area, user 1."}"#);
}
#[tokio::test]
async fn me_with_user_token_still_works() {
let token = token_for(7, "user");
let (status, _) = get("/me", Some(&token)).await;
assert_eq!(status, StatusCode::OK);
}
The user-token test is the one that guards the second gate. If somebody later changes require_admin to return the unauthorized variant for ordinary users, that test fails on the status code. If somebody removes the role layer entirely, it fails too, because the user token would suddenly reach the handler. The test makes the 403 a checked fact instead of a comment in the code.
Run the tests with:
cargo test
Common Beginner Mistakes
Returning 401 for a known user without permission
// Wrong - the user is known, the answer is about permission
match role.as_deref() {
None => Err(AppError::Unauthorized),
Some("admin") => Ok(next.run(request).await),
Some(_) => Err(AppError::Unauthorized),
}
The user proved who they are, so a 401 tells the client to log in again, and logging in again changes nothing. The fix is the forbidden variant. When the identity is known and the rule says no, the answer is 403.
Checking the role before verifying the token
// Wrong - the role comes from a token nobody verified
let claims: Claims = decode_without_verifying(token);
if claims.role != "admin" {
return Err(AppError::Forbidden);
}
A role read from an unverified token is whatever the client wrote in it. Anyone can write "admin" into a token payload, because the payload is readable and editable by design. The signature is the only thing that proves the role was put there by the server. The fix is the order on this page. Verify first, in the auth middleware, and read the role from the verified claims after that.
Stacking the layers in the wrong order
// Wrong - require_admin runs first and finds no user
let admin_routes = Router::new()
.route("/admin", get(admin_handler))
.route_layer(middleware::from_fn(auth_middleware))
.route_layer(middleware::from_fn(require_admin));
Every request gets a 401, including the ones with a valid admin token, because require_admin runs before the user is attached. The fix is to add the role layer first and the auth layer second, so auth ends up outermost and runs first.
Naming the required role in the response
// Wrong - the body tells an attacker which role to aim for
Some(_) => Err(AppError::ValidationError("admin role required".to_string())),
Two things are wrong here. The variant is wrong, because a permission refusal is not a validation failure, so the status would be 422 instead of 403. And the message names the required role, which teaches an attacker exactly what to steal or forge. The fix is the forbidden variant with its single generic word.
Checking the role after doing the work
// Wrong - the report is built before the caller is allowed to see it
async fn admin_report_handler() -> Json<serde_json::Value> {
let report = build_report().await;
Json(report)
}
A handler that builds its response before the role is checked wastes work and risks leaking information through side effects, such as log entries that record that the report was built. The check belongs in the middleware, before the handler runs at all, which is where the working version puts it.
Putting the admin route in the user router
// Wrong - the admin route carries only the auth layer
let user_routes = Router::new()
.route("/me", get(me_handler))
.route("/admin", get(admin_handler))
.route_layer(middleware::from_fn(auth_middleware));
Any signed-in user reaches /admin, because the router that holds it has no role layer. The fix is the separate admin router from the working version, with both layers attached to it.
A role layer without the auth layer is an open door:
require_admin trusts whatever it finds in the extensions. On a route that carries only the role layer and no auth layer, the extensions hold nothing, and every request gets a 401, which looks safe but is an accident. Worse, if any other middleware on that route inserted an AuthUser without verifying a token, the role layer would trust it. Always pair the role layer with the auth layer, on the same router, in the order shown on this page.
Final Complete Example
Here is the full project from this page, with the error type, the token code, both middlewares, two routers with their own layers, 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 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 async fn require_admin(
request: Request,
next: Next,
) -> Result<Response, AppError> {
let role = request
.extensions()
.get::<AuthUser>()
.map(|user| user.role.clone());
match role.as_deref() {
None => Err(AppError::Unauthorized),
Some("admin") => Ok(next.run(request).await),
Some(_) => Err(AppError::Forbidden),
}
}
pub mod auth;
pub mod errors;
use axum::{
Json, Router,
extract::Extension,
middleware,
routing::get,
};
use serde_json::json;
use auth::{AuthUser, auth_middleware, require_admin};
use errors::AppError;
pub fn app() -> Router {
let user_routes = Router::new()
.route("/me", get(me_handler))
.route("/settings", get(settings_handler))
.route_layer(middleware::from_fn(auth_middleware));
let admin_routes = Router::new()
.route("/admin", get(admin_handler))
.route("/admin/report", get(admin_report_handler))
.route_layer(middleware::from_fn(require_admin))
.route_layer(middleware::from_fn(auth_middleware));
Router::new()
.route("/public", get(public_handler))
.merge(user_routes)
.merge(admin_routes)
}
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" }))
}
async fn admin_handler(
Extension(user): Extension<AuthUser>,
) -> Json<serde_json::Value> {
Json(json!({ "message": format!("Welcome to the admin area, user {}.", user.user_id) }))
}
async fn admin_report_handler() -> Json<serde_json::Value> {
Json(json!({ "report": "weekly totals", "signups": 42 }))
}
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 framework that covers every protected route in this project is a two-question test, asked in order. First, who is asking? If nobody can be identified, the answer is 401, and the client can fix it by proving its identity. Second, may this user do this? If the user is known and the rule says no, the answer is 403, and no amount of re-logging changes it. Only when both questions pass does the handler do its work.
That order is what keeps the error handling honest, and the layering is what keeps it maintainable. A single check that mixed identity and permission would return one status for two different failures, and the client would never know whether to log in again or to stop asking. Two small middlewares, stacked with the producer added last so it runs first, give the client exactly the information it needs, and give the project a shape where a new role or a new protected group slots in as one more router with its own layers, instead of a rewrite of the check.