Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 38 ยท Authentication and Errors

Authentication Middleware and Authorization

Protect Axum routes with a custom FromRequestParts extractor or from_fn middleware, add role checks and per-resource ownership rules, and understand 401 versus 403, with runnable stand-ins.

Issuing a token is half the job. The other half is checking it on every protected request and deciding what the caller may do. Two words get mixed up: authentication answers "who are you?" (a valid token proves it) and authorization answers "are you allowed to do this?" (roles, ownership, permissions). Axum gives you two clean places to implement them: a custom extractor for per-handler identity and middleware for protecting whole groups of routes.

The real code needs Axum, so it is read-only. Runnable stand-ins model the checks with plain functions so you can test the decision logic. For the token itself, see JWT authentication.

401 versus 403

  • 401 Unauthorized: the request has no valid credentials (missing, malformed or expired token). The client should authenticate. Include a WWW-Authenticate: Bearer header.
  • 403 Forbidden: the caller is known but not allowed. Logging in again will not help.
  • 404 Not Found is sometimes better than 403 for resources the caller should not even know exist, such as another user's private document.

An extractor that authenticates

Anything that implements FromRequestParts can be used as a handler argument. Put the identity check there, and every handler that wants authentication simply asks for it in its signature:

Rust
// Real code: read-only. Axum 0.8 (no #[async_trait] needed).
use axum::{extract::FromRequestParts, http::request::Parts};

pub struct AuthUser {
    pub id: i64,
    pub role: String,
}

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

    async fn from_request_parts(parts: &mut Parts, state: &AppState) -> Result<Self, Self::Rejection> {
        let header = parts
            .headers
            .get(axum::http::header::AUTHORIZATION)
            .and_then(|v| v.to_str().ok())
            .ok_or(AppError::Unauthorized)?;
        let token = header.strip_prefix("Bearer ").ok_or(AppError::Unauthorized)?;
        let claims = verify_token(token, state.jwt_secret.as_bytes())?;
        Ok(AuthUser { id: claims.sub, role: claims.role })
    }
}

async fn me(user: AuthUser) -> Json<serde_json::Value> {
    Json(serde_json::json!({ "id": user.id, "role": user.role }))
}

If extraction fails, the handler is never called and the rejection (AppError::Unauthorized, so a 401 JSON body) is returned. For optional authentication (a page that differs for guests), implement OptionalFromRequestParts and take Option<AuthUser>.

Middleware for a group of routes

When every route in a group needs login, a middleware avoids repeating the extractor and can add the user to the request for later handlers:

Rust
use axum::{extract::{Request, State}, middleware::{self, Next}, response::Response};

async fn require_auth(State(state): State<AppState>, mut req: Request, next: Next) -> Result<Response, AppError> {
    let token = req
        .headers()
        .get("authorization")
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix("Bearer "))
        .ok_or(AppError::Unauthorized)?;
    let claims = verify_token(token, state.jwt_secret.as_bytes())?;
    req.extensions_mut().insert(claims); // handlers read it with Extension<Claims>
    Ok(next.run(req).await)
}

let protected = Router::new()
    .route("/todos", get(list).post(create))
    .route_layer(middleware::from_fn_with_state(state.clone(), require_auth));

let app = Router::new()
    .route("/login", post(login))
    .merge(protected)
    .with_state(state);

Using route_layer means unknown paths still return 404 rather than 401, as the Tower lesson explained. Keep /login, /register and /health outside the protected router.

Role-based authorization

Roles (user, editor, admin) are the simplest authorization model. Check them either in the handler or with a small extractor that wraps AuthUser:

Rust
pub struct AdminUser(pub AuthUser);

impl FromRequestParts<AppState> for AdminUser {
    type Rejection = AppError;

    async fn from_request_parts(parts: &mut Parts, state: &AppState) -> Result<Self, Self::Rejection> {
        let user = AuthUser::from_request_parts(parts, state).await?;
        if user.role == "admin" { Ok(AdminUser(user)) } else { Err(AppError::Forbidden) }
    }
}

async fn delete_user(_: AdminUser, Path(id): Path<i64>, State(db): State<PgPool>) -> Result<StatusCode, AppError> {
    // only admins reach this body
    Ok(StatusCode::NO_CONTENT)
}

The signature itself documents the requirement: AdminUser in the arguments means "admins only", checked before any code runs.

Ownership checks

Roles are not enough. A normal user may edit their own todos but not someone else's. This is the most commonly forgotten check (an "insecure direct object reference"). Put the owner in the SQL so the database enforces it:

Rust
let result = sqlx::query("DELETE FROM todos WHERE id = $1 AND owner_id = $2")
    .bind(id)
    .bind(user.id)
    .execute(&db)
    .await?;
if result.rows_affected() == 0 {
    return Err(AppError::NotFound); // not found OR not yours: do not reveal which
}

Stand-in: extractor and guards

Rust Authenticate, then authorize (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Permission-based access

When roles multiply, switch to explicit permissions (todos:write, users:delete) attached to roles or users, and check permissions rather than role names. The decision logic stays a pure function you can unit test:

Rust A pure permission check (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Default to deny: an unknown role (the ghost line) gets nothing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A request carries a valid token for a normal user but targets an admin-only route. Which status?

    The caller is authenticated but not authorized. 401 is for missing or invalid credentials.
  2. 2. What does implementing FromRequestParts for AuthUser let you do?

    Extractors run before the handler. A failed extraction returns its rejection and the handler never executes.
  3. 3. Why use route_layer rather than layer for an auth middleware?

    route_layer only wraps matched routes.
  4. 4. What is the best way to prevent users editing each other's rows?

    Role checks do not know who owns a row. The owner condition must be enforced on the server for every access.

Summary

  • Authentication proves identity (401 on failure); authorization decides access (403).
  • A FromRequestParts extractor makes protected handlers declare their requirement in the signature.
  • from_fn_with_state middleware plus route_layer protects a group of routes.
  • Check roles or permissions, and always enforce ownership in the query.
  • Default to deny.

Next: Testing Handlers with oneshot