Unauthorized error variant

Learn how to add an Unauthorized variant to AppError that answers unauthenticated requests with status 401 and a shared JSON error body

Some routes are only for people the server knows. A profile page, a settings page, or a list of personal notes means nothing without knowing whose profile, settings, or notes were asked for. When a request arrives without proof of who sent it, the server answers 401 Unauthorized. This page adds the variant that produces that answer.

Where This Fits

The HandlerResult alias shortened every handler signature, so returning an error is now a one-line affair. This page uses that shorthand to add a new kind of failure, a request that cannot be tied to any known user. The alias does not change, the error file grows by one variant, and one handler learns to check for credentials.

Think of the difference between a locked door and a locked room inside a house. The front door asks who you are. If you cannot say, you stay outside, and nobody asks what you wanted inside. That is the 401 response. The room inside asks a different question, whether you are allowed in, and that question only makes sense once the front door has let you through.

The Smallest Working Version

Adding the variant takes three small edits in errors.rs. A new line in the enum, a new message, and a new arm in the status mapping. Everything else in the file stays exactly as it was.

src/errors.rs
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,
}

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,
        };
        let body = Json(json!({ "error": self.to_string() }));
        (status, body).into_response()
    }
}

impl From<std::io::Error> for AppError {
    fn from(error: std::io::Error) -> Self {
        eprintln!("io error: {error}");
        AppError::InternalError
    }
}

impl From<serde_json::Error> for AppError {
    fn from(error: serde_json::Error) -> Self {
        eprintln!("json error: {error}");
        AppError::InternalError
    }
}

pub type HandlerResult<T> = Result<T, AppError>;

The variant carries no data, because there is nothing useful to attach to it. The message is the single word unauthorized, which is the text the client sees in the JSON body. The status arm maps it to StatusCode::UNAUTHORIZED, which is the constant for 401. The body construction is shared with every other variant, so the response shape is identical to the one used for a missing note or a broken file.

The handler that uses the variant checks the Authorization header, which is the standard HTTP header for carrying credentials. A header map is a collection of request headers, and Axum can hand it to a handler as an extractor, which is a function argument that Axum fills in from the incoming request.

src/lib.rs
pub mod errors;

use axum::{
    Json, Router,
    http::{HeaderMap, header},
    routing::get,
};
use errors::{AppError, HandlerResult};
use serde_json::json;

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

async fn profile(headers: HeaderMap) -> HandlerResult<Json<serde_json::Value>> {
    require_token(&headers)?;
    Ok(Json(json!({ "name": "Ada", "email": "ada@example.com" })))
}

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

fn require_token(headers: &HeaderMap) -> HandlerResult<()> {
    match bearer_token(headers) {
        Some("secret-token") => Ok(()),
        _ => Err(AppError::Unauthorized),
    }
}

The handler itself is two lines. It calls the helper, and on success returns a small JSON object with a name and an email. The helper does the real work. It reads the Authorization header, turns the value into text, and strips the Bearer prefix, which is the scheme name that marks the value as a bearer token, a token the holder simply presents to prove who they are. If what remains equals the expected token, the helper returns success. Anything else, a missing header, a garbled value, or a wrong token, returns the unauthorized variant.

src/main.rs
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();
}

The entry point is unchanged. Adding a variant touches the error file and the handlers that use it, never the startup code.

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

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
thiserror = "2.0"
serde = { version = "1", features = ["derive"] }
serde_json = "1"

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

Running the server and requesting the route without a header shows the new response.

curl http://127.0.0.1:3000/profile
{"error":"unauthorized"}

The status code behind that body is 401, which curl hides unless asked. Asking for the headers shows it.

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

{"error":"unauthorized"}

A wrong token gets exactly the same answer, which is deliberate. The server does not say whether the header was missing or the token was wrong, because that distinction helps an attacker and nobody else.

curl -H "Authorization: Bearer wrong-token" http://127.0.0.1:3000/profile
{"error":"unauthorized"}

The right token opens the door.

curl -H "Authorization: Bearer secret-token" http://127.0.0.1:3000/profile
{"email":"ada@example.com","name":"Ada"}

Working Setup:

If the request without a token returns 401 with the body {"error":"unauthorized"}, the wrong token returns the same, and the right token returns the profile, the variant is wired up correctly. All three outcomes come from one check and one variant.

What 401 Means in Plain Words

Status 401 means the server does not know who is asking. The word in the status name is Unauthorized, which is a confusing name, because in everyday language it sounds like permission. In HTTP it means authentication failed, and authentication is the act of proving identity. The request arrived without credentials, or with credentials the server does not accept, so the server cannot tie the request to any user at all.

That meaning has a practical consequence. A 401 answer is an invitation to try again with credentials. A client that receives it can ask the user to log in, fetch a fresh token, and repeat the request. The retry might succeed, because the problem was missing proof, not a rule the user broke. Keep that test in mind. If logging in again could fix the request, the answer is 401.

The variant on this page carries no message from the server about which user was expected or why the token failed. That silence is part of the design. A response that says "no such user" versus "wrong password" lets an attacker probe which accounts exist. One word, unauthorized, covers every failure the same way.

Never Hard Code a Real Token:

The token secret-token in this page is a teaching stand-in, not a pattern to copy. A real application checks credentials against a session store, a database, or an identity service, and it never stores a secret in source code. Anyone who can read the source can read a hard-coded token, and then the check is worth nothing. Replace the comparison with a real lookup before the code leaves the learning project.

The Require Token Helper, Piece by Piece

The work is split across two small functions. bearer_token pulls the token out of the headers and returns an Option, a value that is either present or absent. require_token decides whether that token is accepted. It returns HandlerResult<()>, which is a result with no success value, because the only thing a caller needs to know is whether the check passed. The ? operator in the handler turns a failure into an early return, so the handler body never runs for an unauthenticated request.

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

fn require_token(headers: &HeaderMap) -> HandlerResult<()> {
    match bearer_token(headers) {
        Some("secret-token") => Ok(()),
        _ => Err(AppError::Unauthorized),
    }
}

The first function, bearer_token, pulls the token out of the headers. The first call, headers.get(header::AUTHORIZATION), looks up the header by its standard name. It returns an Option, which is a value that is either present or absent, because the header might not be there at all. The next call, and_then(|value| value.to_str().ok()), turns the raw header value into text. A header value is bytes, and to_str fails if those bytes are not valid text, so ok() turns that failure into an absent value rather than an error. The last call, and_then(|value| value.strip_prefix("Bearer ")), removes the scheme prefix and returns the token itself, or an absent value if the prefix is not there.

The match at the end handles the two cases. A token that equals the expected string returns success. Every other case, missing header, non-text value, wrong scheme, wrong token, falls through to the catch-all arm and returns the unauthorized variant. Writing the check as one chain of and_then calls means each failure mode collapses into the same absent value, and the handler never needs to distinguish them.

The helper is a plain function, not an async one, because it does no waiting. It only reads a header map that is already in memory. Keeping it synchronous makes it easy to call from any handler and easy to test on its own.

Checking Early, Before Any Other Work

The handler calls require_token as its first line, before reading a body, opening a file, or touching any other data. That order matters for two reasons. It keeps unauthenticated requests cheap, because the server does no work for a request it will reject. And it keeps unauthenticated requests blind, because the server reveals nothing about whether the requested data exists before it knows who is asking.

async fn profile(headers: HeaderMap) -> HandlerResult<Json<serde_json::Value>> {
    require_token(&headers)?;
    Ok(Json(json!({ "name": "Ada", "email": "ada@example.com" })))
}

The ? after the helper call is what enforces the order. On failure it returns the error from the handler immediately, and the lines below never run. On success it unwraps the empty success value and execution continues. A handler that does its work first and checks credentials afterwards has the order backwards, and the mistake is easy to make when the check is added to an existing handler as an afterthought.

One subtlety deserves a plain sentence. Extractors run before the handler body, in the order the arguments are listed. If a handler takes both a HeaderMap and a JSON body, a malformed body is rejected before the handler body runs, which means before the token check runs. An unauthenticated request with a broken body therefore gets the body error, not the 401. That is a consequence of how extractors work, not a bug in the check. Keeping the token check as the first line of the body is still the right habit, and it covers every failure that reaches the body.

A Second Route Sharing the Same Check

One helper serves any number of routes. A settings route needs the same proof as the profile route, and it calls the same function with no new code in the error file.

src/lib.rs
pub fn app() -> Router {
    Router::new()
        .route("/profile", get(profile))
        .route("/settings", get(settings))
}

async fn settings(headers: HeaderMap) -> HandlerResult<Json<serde_json::Value>> {
    require_token(&headers)?;
    Ok(Json(json!({ "theme": "dark", "language": "en" })))
}

Both routes answer 401 without a token and 200 with one. The check lives in one place, so changing the token, or replacing the comparison with a real lookup later, touches one function. A project that copies the header parsing into every handler ends up with several copies that drift apart, and the drift is where security mistakes hide.

Routes That Do Not Need a Token

Not every route needs the check. A public route, such as a home page or a list of public notes, simply does not call require_token. The check is per handler, not global, which means each route decides for itself whether it needs proof of identity. That is the right granularity for a small project. A route that serves public data stays open, a route that serves personal data calls the helper, and the router table shows at a glance which routes are protected, because the call sits on the first line of each protected handler. When the project grows large enough that most routes need the check, a shared layer can apply it to a whole group at once, but that is a different tool for a later stage, and the per-handler check on this page is the foundation it builds on.

A Plain Text Diagram of the Flow

The request passes through the check before it reaches the data, and the two outcomes split at the helper.

request arrives with headers
        |
        v
handler calls require_token
        |
        +-- token matches --> handler builds the JSON profile
        |                          |
        |                          v
        |                     200 + {"name": "Ada", ...}
        |
        +-- token missing or wrong --> AppError::Unauthorized
                                       |
                                       v
                                  401 + {"error": "unauthorized"}

The diagram has no third branch, because the helper deliberately collapses every failure into one answer. That collapse is a feature. A client sees one response for every authentication failure, and an attacker learns nothing from probing the difference.

Testing It

Three tests cover the three outcomes, no token, wrong token, and right token. Each test sends a request through the router with oneshot and checks the status and the exact body.

tests/unauthorized_test.rs
use axum::{
    body::{Body, to_bytes},
    http::{Request, StatusCode},
};
use axum_project::app;
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_profile(token: Option<&str>) -> (StatusCode, String) {
    let mut builder = Request::builder().uri("/profile");
    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 profile_without_token_is_unauthorized() {
    let (status, body) = get_profile(None).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
    assert_eq!(body, r#"{"error":"unauthorized"}"#);
}

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

#[tokio::test]
async fn profile_with_right_token_returns_profile() {
    let (status, body) = get_profile(Some("secret-token")).await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body, r#"{"email":"ada@example.com","name":"Ada"}"#);
}

The shared get_profile helper builds the request with or without a header, so each test stays short. The wrong-token test is the one that guards the design decision. If somebody later changes the code to say which failure happened, that test still passes on status but the body assertion would need to change, which forces the change to be deliberate rather than accidental.

Common Beginner Mistakes

Returning 403 for a Missing Token

// Wrong - the server does not know who is asking yet
fn require_token(headers: &HeaderMap) -> HandlerResult<()> {
    match bearer_token(headers) {
        Some("secret-token") => Ok(()),
        _ => Err(AppError::Forbidden),
    }
}

A missing token is not a permission problem. The server has no user to check permission against, so 403 is the wrong status. The fix is the unauthorized variant. The rule to remember is the retry test. If logging in could fix the request, the answer is 401. A 403 answer says logging in again changes nothing.

Do Not Explain Which Part Failed:

A response body that says "token expired" for one failure and "token missing" for another teaches an attacker how the check works. Keep one body for every authentication failure. The detail belongs in the server log, where the developer can read it, not in the response, where anyone can read it.

Checking Credentials After Doing the Work

// Wrong - the note is loaded before the caller is known
async fn profile(headers: HeaderMap) -> HandlerResult<Json<serde_json::Value>> {
    let data = load_profile_data().await?;
    require_token(&headers)?;
    Ok(Json(data))
}

This handler loads the profile before checking the token. An unauthenticated request still pays the cost of the load, and any side effect in the load, such as a log entry or a cache fill, happens for a request that should have been turned away at the door. The fix is to move the check to the first line, as the working version does.

Comparing the Whole Header Value to the Token

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

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

Returning a Different Message for Each Failure

// Wrong - two bodies for one kind of failure
match token {
    None => Err(AppError::ValidationError("missing token".to_string())),
    Some(_) => Err(AppError::Unauthorized),
}

A missing token is not a validation failure, and giving it a different body breaks the shared shape. Clients that parse error responses have to handle two shapes for one problem, and the distinction leaks information about the check. One variant, one body, for every authentication failure.

Treating 401 as a General Error

// Wrong - a database failure is not an authentication failure
async fn profile(headers: HeaderMap) -> HandlerResult<Json<serde_json::Value>> {
    require_token(&headers)?;
    let data = load_profile_data().await.map_err(|_| AppError::Unauthorized)?;
    Ok(Json(data))
}

Mapping an unrelated failure to the unauthorized variant tells the client to log in again, when logging in again changes nothing. The client retries, fails again, and the real problem stays hidden. Each failure maps to the variant that names its cause. A database failure is an internal error, and it uses the internal variant.

Final Complete Example

Here is the full project from this page, with the variant, the helper, and two routes that share it.

src/errors.rs
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,
}

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,
        };
        let body = Json(json!({ "error": self.to_string() }));
        (status, body).into_response()
    }
}

impl From<std::io::Error> for AppError {
    fn from(error: std::io::Error) -> Self {
        eprintln!("io error: {error}");
        AppError::InternalError
    }
}

impl From<serde_json::Error> for AppError {
    fn from(error: serde_json::Error) -> Self {
        eprintln!("json error: {error}");
        AppError::InternalError
    }
}

pub type HandlerResult<T> = Result<T, AppError>;
src/lib.rs
pub mod errors;

use axum::{
    Json, Router,
    http::{HeaderMap, header},
    routing::get,
};
use errors::{AppError, HandlerResult};
use serde_json::json;

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

async fn profile(headers: HeaderMap) -> HandlerResult<Json<serde_json::Value>> {
    require_token(&headers)?;
    Ok(Json(json!({ "name": "Ada", "email": "ada@example.com" })))
}

async fn settings(headers: HeaderMap) -> HandlerResult<Json<serde_json::Value>> {
    require_token(&headers)?;
    Ok(Json(json!({ "theme": "dark", "language": "en" })))
}

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

fn require_token(headers: &HeaderMap) -> HandlerResult<()> {
    match bearer_token(headers) {
        Some("secret-token") => Ok(()),
        _ => Err(AppError::Unauthorized),
    }
}
Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
thiserror = "2.0"
serde = { version = "1", features = ["derive"] }
serde_json = "1"

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

Run the checks with these commands.

cargo check
cargo test
cargo run

Production 401 Responses Carry One More Header:

Real authentication systems usually add a WWW-Authenticate header to a 401 response, naming the scheme the client should use, such as Bearer. This page keeps the shared JSON shape and does not add that header, because the shape is the contract this project is building. Adding the header later changes no body and no status, so the responses shown here stay correct.

Summary

The decision that matters on this page is not how to read a header. It is what a 401 means and when to use it. A 401 says the server does not know who is asking, and it invites the client to prove its identity and try again. That meaning separates it from every other error in the project. A missing note is a fact about the data. A broken file is a fact about the server. A missing token is a fact about the request, and it is the only one of the three that a login can repair.

The framework to carry forward is the retry test. When a request fails, ask whether the same user, logged in properly, could make it succeed. If yes, the answer is 401. If the user is already known and the answer would still be no, the failure belongs to a different variant, the one that deals with permission rather than identity. That variant is the subject of the idea that follows this one, and the two together cover the whole question of who may do what.