Authorization Parsing

How to parse and validate the Authorization header inside custom Axum extractors.

When you build an API that protects certain routes, the request arrives with an Authorization header. This header carries credentials in a specific format such as Bearer <token> or Basic <base64-encoded-username-and-password>. Your job is to read that header, check that it uses a scheme your application supports, extract the actual credential, validate it (for example by checking a token or matching a username/password), and then either pass the authenticated user into your handler or reject the request with an appropriate error.

This page covers how to perform that parsing work inside a custom extractor. You will learn several ways to read the Authorization header, how to handle both Bearer tokens and Basic authentication, how to return meaningful errors when the header is missing or malformed, and how to integrate the parsed result into an extractor type like AuthUser. Everything here builds on the idea of a custom extractor, but the focus is strictly on the parsing logic - not on creating the extractor trait implementation from scratch.

Reading the Authorization Header Directly

Before creating a custom extractor, it helps to see the raw header. Axum provides the HeaderMap extractor for accessing all request headers. The following minimal example reads the Authorization header and returns its value as a String.

src/main.rs
use axum::{
    http::{header::AUTHORIZATION, HeaderMap},
    response::IntoResponse,
    routing::get,
    Router,
};
async fn show_auth_header(headers: HeaderMap) -> impl IntoResponse {
    match headers.get(AUTHORIZATION) {
        Some(value) => value.to_str().unwrap_or("invalid header").to_string(),
        None => "no Authorization header".to_string(),
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(show_auth_header));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Run the server and send a request with an Authorization header:

curl -H "Authorization: Bearer my-secret-token" http://127.0.0.1:3000/

You will see Bearer my-secret-token printed in the response. This works, but it is not reusable. Every handler that needs authentication would have to repeat this code. Worse, the handler receives a raw String and still has to parse out the scheme and the token by itself. That is where a custom extractor becomes useful.

Parsing a Bearer Token in a Custom Extractor

The goal is to create an extractor that, when added as a parameter to a handler, automatically reads the Authorization header, checks that it starts with Bearer , extracts the token part, and returns it wrapped in a type you define. If anything goes wrong, the handler is never called; Axum instead sends back an error response.

We will implement the FromRequestParts trait because reading a header does not require consuming the request body. The extractor will produce an AuthUser that contains the token string. Later you could expand AuthUser with real user data, but for now the token is enough.

The example below defines AuthUser, implements FromRequestParts<S> for it, and uses the extractor in a handler.

src/main.rs
use axum::{
    extract::FromRequestParts,
    http::{header::AUTHORIZATION, request::Parts, StatusCode},
    response::IntoResponse,
    routing::get,
    Router,
};
pub struct AuthUser {
    pub token: String,
}
impl<S> FromRequestParts<S> for AuthUser
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let auth_header = parts
            .headers
            .get(AUTHORIZATION)
            .ok_or((StatusCode::UNAUTHORIZED, "missing Authorization header"))?;
        let auth_str = auth_header
            .to_str()
            .map_err(|_| (StatusCode::BAD_REQUEST, "Authorization header is not valid UTF-8"))?;
        if let Some(token) = auth_str.strip_prefix("Bearer ") {
            Ok(AuthUser {
                token: token.to_string(),
            })
        } else {
            Err((StatusCode::UNAUTHORIZED, "expected Bearer authentication"))
        }
    }
}
async fn protected_route(user: AuthUser) -> impl IntoResponse {
    format!("You are authenticated with token: {}", user.token)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/protected", get(protected_route));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Test it with curl:

curl http://127.0.0.1:3000/protected

You will receive a 401 Unauthorized with the body missing Authorization header.

Now include the header:

curl -H "Authorization: Bearer secret123" http://127.0.0.1:3000/protected

The response is You are authenticated with token: secret123.

The extractor works because from_request_parts runs before the handler. If it returns Ok, Axum passes the value to the handler. If it returns Err, the rejection type - here (StatusCode, &'static str) - is converted into a response automatically and the handler is skipped.

Case and Prefix Sensitivity:

The strip_prefix("Bearer ") check is case‑sensitive. The HTTP authentication scheme names are case‑insensitive according to RFC 7235, so bearer or BEARER would also be valid in the wild. Many real APIs either accept only one exact form or perform a case‑insensitive comparison. Decide which behavior your API needs and implement it consistently.

Supporting Multiple Whitespace Characters

The HTTP specification allows any number of spaces or tabs between the scheme and the credentials. The simple strip_prefix("Bearer ") only matches exactly one space. If a client sends Bearer mytoken (multiple spaces) or Bearer\tmytoken (a tab), the prefix check fails and the request is rejected.

A more robust parser splits the header on the first whitespace character and then trims the credential part. The code below uses split_once(char::is_whitespace) followed by .trim(), which handles any combination of spaces and tabs after the scheme.

src/main.rs
use axum::{
    extract::FromRequestParts,
    http::{header::AUTHORIZATION, request::Parts, StatusCode},
    response::IntoResponse,
    routing::get,
    Router,
};
pub struct AuthUser {
    pub token: String,
}
impl<S> FromRequestParts<S> for AuthUser
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let auth_header = parts
            .headers
            .get(AUTHORIZATION)
            .ok_or((StatusCode::UNAUTHORIZED, "missing Authorization header"))?;
        let auth_str = auth_header
            .to_str()
            .map_err(|_| (StatusCode::BAD_REQUEST, "invalid header encoding"))?;
        // Split on the first whitespace after the scheme.
        // Example: "Bearer   abc" -> ("Bearer", "abc")
        //          "Basic   dXNlcjpwYXNz" -> ("Basic", "dXNlcjpwYXNz")
        let (scheme, credentials) = auth_str
            .split_once(char::is_whitespace)
            .ok_or((StatusCode::BAD_REQUEST, "malformed Authorization header"))?;
        if !scheme.eq_ignore_ascii_case("Bearer") {
            return Err((StatusCode::UNAUTHORIZED, "unsupported authentication scheme"));
        }
        let token = credentials.trim();
        if token.is_empty() {
            return Err((StatusCode::UNAUTHORIZED, "empty token"));
        }
        Ok(AuthUser {
            token: token.to_string(),
        })
    }
}
async fn protected_route(user: AuthUser) -> impl IntoResponse {
    format!("Authenticated with token: {}", user.token)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/protected", get(protected_route));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Now both of these requests succeed:

curl -H "Authorization: Bearer secret" http://127.0.0.1:3000/protected
curl -H "Authorization: Bearer    another" http://127.0.0.1:3000/protected
curl -H "Authorization: Bearer" http://127.0.0.1:3000/protected   # fails: no token

The last request returns 400 with malformed Authorization header, not 401 with empty token: with the header exactly Bearer there is no whitespace at all, so split_once returns None and the ok_or branch runs. The empty token branch only fires when whitespace is present but nothing follows it, which cannot happen over real HTTP because trailing whitespace is stripped from header values before Axum sees them.

Parsing Basic Authentication

Another common scheme is Basic authentication. The Authorization header looks like Basic dXNlcjpwYXNz, where the part after the scheme is a base64‑encoded string of username:password. To support this, the extractor must:

  1. Split the header into scheme and credentials as before.
  2. Check that the scheme is Basic (case‑insensitive).
  3. Decode the base64 credentials.
  4. Split the decoded string on the first colon (:) to get username and password.
  5. Return both values (or a combined AuthUser).

The example below defines Credentials containing username and password. The extractor now returns Credentials instead of AuthUser, but you can name it whatever fits your application.

src/main.rs
use axum::{
    extract::FromRequestParts,
    http::{header::AUTHORIZATION, request::Parts, StatusCode},
    response::IntoResponse,
    routing::get,
    Router,
};
pub struct Credentials {
    pub username: String,
    pub password: String,
}
impl<S> FromRequestParts<S> for Credentials
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let auth_header = parts
            .headers
            .get(AUTHORIZATION)
            .ok_or((StatusCode::UNAUTHORIZED, "missing Authorization header"))?;
        let auth_str = auth_header
            .to_str()
            .map_err(|_| (StatusCode::BAD_REQUEST, "invalid header encoding"))?;
        let (scheme, encoded) = auth_str
            .split_once(char::is_whitespace)
            .ok_or((StatusCode::BAD_REQUEST, "malformed Authorization header"))?;
        if !scheme.eq_ignore_ascii_case("Basic") {
            return Err((StatusCode::UNAUTHORIZED, "expected Basic authentication"));
        }
        let decoded = base64_decode(encoded.trim())
            .map_err(|_| (StatusCode::BAD_REQUEST, "invalid base64 in Basic credentials"))?;
        let decoded_str = String::from_utf8(decoded)
            .map_err(|_| (StatusCode::BAD_REQUEST, "credentials are not valid UTF-8"))?;
        let (username, password) = decoded_str
            .split_once(':')
            .ok_or((StatusCode::BAD_REQUEST, "Basic credentials must be username:password"))?;
        Ok(Credentials {
            username: username.to_string(),
            password: password.to_string(),
        })
    }
}
fn base64_decode(input: &str) -> Result<Vec<u8>, base64::DecodeError> {
    use base64::{engine::general_purpose, Engine as _};
    general_purpose::STANDARD.decode(input)
}
async fn login(creds: Credentials) -> impl IntoResponse {
    format!("Welcome, {}!", creds.username)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/login", get(login));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

For this to compile you must add the base64 crate to your Cargo.toml:

Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
base64 = "0.22"

Test the Basic flow by first encoding alice:secret as base64. In most shells you can do:

echo -n "alice:secret" | base64

That outputs YWxpY2U6c2VjcmV0. Now send:

curl -H "Authorization: Basic YWxpY2U6c2VjcmV0" http://127.0.0.1:3000/login

The response is Welcome, alice!.

If you send a malformed base64 string or a decoded string without a colon, the extractor returns 400 Bad Request with a descriptive message.

Basic Authentication Is Not Secure on Its Own:

Basic authentication sends the username and password as base64, which is not encryption. Anyone who intercepts the request can decode it instantly. Always use HTTPS when accepting Basic credentials in production. In most modern APIs, Bearer tokens are preferred for their flexibility and server‑side revocability.

Combining Bearer and Basic Support with One Extractor

Sometimes an API must accept both Bearer tokens and Basic credentials depending on the client. You can create a single extractor that returns an enum representing either kind of authentication. The parsing logic tries Bearer first, and if that fails, tries Basic. The extractor returns AuthMethod::Bearer(token) or AuthMethod::Basic(username, password).

Here is a complete example:

src/main.rs
use axum::{
    extract::FromRequestParts,
    http::{header::AUTHORIZATION, request::Parts, StatusCode},
    response::IntoResponse,
    routing::get,
    Router,
};
pub enum AuthMethod {
    Bearer(String),
    Basic { username: String, password: String },
}
impl<S> FromRequestParts<S> for AuthMethod
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let auth_header = parts
            .headers
            .get(AUTHORIZATION)
            .ok_or((StatusCode::UNAUTHORIZED, "missing Authorization header"))?;
        let auth_str = auth_header
            .to_str()
            .map_err(|_| (StatusCode::BAD_REQUEST, "invalid header encoding"))?;
        let (scheme, credentials) = auth_str
            .split_once(char::is_whitespace)
            .ok_or((StatusCode::BAD_REQUEST, "malformed Authorization header"))?;
        if scheme.eq_ignore_ascii_case("Bearer") {
            let token = credentials.trim().to_string();
            if token.is_empty() {
                return Err((StatusCode::UNAUTHORIZED, "empty Bearer token"));
            }
            return Ok(AuthMethod::Bearer(token));
        }
        if scheme.eq_ignore_ascii_case("Basic") {
            let decoded = base64_decode(credentials.trim())
                .map_err(|_| (StatusCode::BAD_REQUEST, "invalid base64"))?;
            let decoded_str = String::from_utf8(decoded)
                .map_err(|_| (StatusCode::BAD_REQUEST, "credentials not UTF-8"))?;
            let (username, password) = decoded_str
                .split_once(':')
                .ok_or((StatusCode::BAD_REQUEST, "Basic credentials must be username:password"))?;
            return Ok(AuthMethod::Basic {
                username: username.to_string(),
                password: password.to_string(),
            });
        }
        Err((StatusCode::UNAUTHORIZED, "unsupported authentication scheme"))
    }
}
fn base64_decode(input: &str) -> Result<Vec<u8>, base64::DecodeError> {
    use base64::{engine::general_purpose, Engine as _};
    general_purpose::STANDARD.decode(input)
}
async fn auth_info(auth: AuthMethod) -> impl IntoResponse {
    match auth {
        AuthMethod::Bearer(token) => format!("Bearer token: {}", token),
        AuthMethod::Basic { username, .. } => format!("Basic user: {}", username),
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/auth", get(auth_info));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This design keeps all authentication logic in one place and lets handlers match on the variant they need.

Multiple Schemes Supported Correctly:

With this extractor, both of these requests work:

  • curl -H "Authorization: Bearer tok123" http://127.0.0.1:3000/auth → Bearer token: tok123
  • curl -H "Authorization: Basic $(echo -n bob:pass | base64)" http://127.0.0.1:3000/auth → Basic user: bob

If the scheme is neither Bearer nor Basic, the extractor returns 401 Unauthorized with unsupported authentication scheme.

Using TypedHeader from axum-extra for Cleaner Access

Axum's HeaderMap works, but the TypedHeader extractor from the axum-extra crate gives you a strongly typed way to access headers. It also implements OptionalFromRequestParts, meaning you can use Option<TypedHeader<Authorization>> to get None when the header is missing instead of an immediate rejection. This is useful when a route may or may not require authentication.

First add axum-extra to your Cargo.toml:

Cargo.toml
[dependencies]
axum = "0.8"
axum-extra = { version = "0.12", features = ["typed-header"] }
tokio = { version = "1", features = ["full"] }
base64 = "0.22"

Now implement the extractor using TypedHeader<Authorization<Bearer>> (the Authorization typed header from axum_extra::headers). This typed header already parses the scheme and exposes the token.

src/main.rs
use axum::{
    extract::FromRequestParts,
    http::request::Parts,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use axum_extra::{
    headers::{authorization::Bearer, Authorization},
    TypedHeader,
};
pub struct AuthUser {
    pub token: String,
}
impl<S> FromRequestParts<S> for AuthUser
where
    S: Send + Sync,
{
    type Rejection = Response;
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        // TypedHeader<Authorization<Bearer>> will reject if the header is missing or
        // does not use the Bearer scheme.
        let TypedHeader(Authorization(bearer)) =
            TypedHeader::<Authorization<Bearer>>::from_request_parts(parts, _state)
                .await
                .map_err(|err| err.into_response())?;
        Ok(AuthUser {
            token: bearer.token().to_string(),
        })
    }
}
async fn protected(user: AuthUser) -> impl IntoResponse {
    format!("Token: {}", user.token)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/protected", get(protected));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Notice that the rejection type is now Response. TypedHeader produces a rich rejection that Axum can turn into a meaningful HTTP response, often with a descriptive body. The from_request_parts method is a plain async fn: Axum 0.8 uses return-position impl Future, so no async_trait macro is needed, and Axum does not re-export one.

This approach is less code for the Bearer case, and the same holds for Basic: axum_extra::headers::authorization::Basic stores the username and password as separate fields, already decoded from base64. So you can use Authorization<Basic> directly, with no manual base64 decoding.

Here is a version that extracts Basic credentials with TypedHeader:

src/main.rs
use axum::{
    extract::FromRequestParts,
    http::request::Parts,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use axum_extra::{
    headers::{authorization::Basic, Authorization},
    TypedHeader,
};
pub struct BasicUser {
    pub username: String,
    pub password: String,
}
impl<S> FromRequestParts<S> for BasicUser
where
    S: Send + Sync,
{
    type Rejection = Response;
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let TypedHeader(Authorization(basic)) =
            TypedHeader::<Authorization<Basic>>::from_request_parts(parts, _state)
                .await
                .map_err(|err| err.into_response())?;
        Ok(BasicUser {
            username: basic.username().to_string(),
            password: basic.password().to_string(),
        })
    }
}
async fn basic_info(user: BasicUser) -> impl IntoResponse {
    format!("Username: {}", user.username)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/basic", get(basic_info));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

No manual base64 decoding needed - axum-extra handles it and rejects invalid input with a proper response.

Which Approach Should You Use?:

If you already depend on axum-extra and only need Bearer or Basic, using TypedHeader reduces boilerplate and gives you well‑tested parsing. If you need a custom scheme, a mix of schemes, or want full control over error messages, the manual HeaderMap approach is clearer and has no extra dependencies. Many production codebases choose one based on team familiarity.

Handling Optional Authorization

Some endpoints allow anonymous access but still benefit from knowing who the user is if credentials are present. For that, use Option<AuthUser> in the handler signature. Axum will call the extractor only if the underlying extractor implements OptionalFromRequestParts (or OptionalFromRequest). Your custom extractor can implement that trait in addition to FromRequestParts to control when None is returned instead of Err.

Below is a custom AuthUser that implements FromRequestParts (rejecting when missing or invalid) and OptionalFromRequestParts (returning None when the header is missing, but still rejecting on malformed header).

src/main.rs
use axum::{
    extract::{FromRequestParts, OptionalFromRequestParts},
    http::{header::AUTHORIZATION, request::Parts, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use axum_extra::{
    headers::{authorization::Bearer, Authorization},
    TypedHeader,
};
pub struct AuthUser {
    pub token: String,
}
impl<S> FromRequestParts<S> for AuthUser
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let auth_header = parts
            .headers
            .get(AUTHORIZATION)
            .ok_or((StatusCode::UNAUTHORIZED, "missing Authorization header"))?;
        let auth_str = auth_header
            .to_str()
            .map_err(|_| (StatusCode::BAD_REQUEST, "invalid header encoding"))?;
        let (scheme, token) = auth_str
            .split_once(char::is_whitespace)
            .ok_or((StatusCode::BAD_REQUEST, "malformed Authorization header"))?;
        if !scheme.eq_ignore_ascii_case("Bearer") {
            return Err((StatusCode::UNAUTHORIZED, "expected Bearer token"));
        }
        Ok(AuthUser {
            token: token.trim().to_string(),
        })
    }
}
impl<S> OptionalFromRequestParts<S> for AuthUser
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);
    async fn from_request_parts(
        parts: &mut Parts,
        state: &S,
    ) -> Result<Option<Self>, Self::Rejection> {
        if parts.headers.contains_key(AUTHORIZATION) {
            // Header exists, try full extraction
            match <Self as FromRequestParts<S>>::from_request_parts(parts, state).await {
                Ok(user) => Ok(Some(user)),
                Err(err) => Err(err),
            }
        } else {
            // No header, return None instead of error
            Ok(None)
        }
    }
}
async fn maybe_auth(user: Option<AuthUser>) -> impl IntoResponse {
    match user {
        Some(u) => format!("Authenticated with token {}", u.token),
        None => "Anonymous access".to_string(),
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/maybe", get(maybe_auth));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Now sending no header gives Anonymous access, while sending a valid Bearer header gives the authenticated message. If the header is present but malformed, the request still fails with an error, because the optional implementation only suppresses the "missing header" case.

Optional Extraction Does Not Mean Ignore Errors:

A common beginner mistake is to think Option<AuthUser> means "never fail authentication". In reality, if the header is present but invalid, the extractor will still reject the request. OptionalFromRequestParts only turns the absence of the data into None. This lets you differentiate between "no credentials provided" and "bad credentials provided".

Custom Error Responses for Authorization Failures

So far the rejection type has been a tuple of StatusCode and a string. That is enough for small APIs, but you may want to return a consistent JSON error body or include additional headers. You can define your own rejection type that implements IntoResponse, and use it as the Rejection in your extractor.

Here is an example using a JSON error response for missing or invalid Authorization headers.

src/main.rs
use axum::{
    extract::FromRequestParts,
    http::{header::AUTHORIZATION, request::Parts, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Json, Router,
};
use serde_json::json;
pub struct AuthUser {
    pub token: String,
}
pub enum AuthError {
    MissingHeader,
    InvalidScheme,
    InvalidUtf8,
    MissingToken,
}
impl IntoResponse for AuthError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AuthError::MissingHeader => (StatusCode::UNAUTHORIZED, "missing Authorization header"),
            AuthError::InvalidScheme => (StatusCode::UNAUTHORIZED, "only Bearer tokens are accepted"),
            AuthError::InvalidUtf8 => (StatusCode::BAD_REQUEST, "header contains invalid characters"),
            AuthError::MissingToken => (StatusCode::UNAUTHORIZED, "Bearer token is empty"),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}
impl<S> FromRequestParts<S> for AuthUser
where
    S: Send + Sync,
{
    type Rejection = AuthError;
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let auth_header = parts
            .headers
            .get(AUTHORIZATION)
            .ok_or(AuthError::MissingHeader)?;
        let auth_str = auth_header
            .to_str()
            .map_err(|_| AuthError::InvalidUtf8)?;
        let (scheme, token) = auth_str
            .split_once(char::is_whitespace)
            .ok_or(AuthError::InvalidScheme)?;
        if !scheme.eq_ignore_ascii_case("Bearer") {
            return Err(AuthError::InvalidScheme);
        }
        if token.trim().is_empty() {
            return Err(AuthError::MissingToken);
        }
        Ok(AuthUser {
            token: token.trim().to_string(),
        })
    }
}
async fn protected(user: AuthUser) -> impl IntoResponse {
    format!("Token: {}", user.token)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/protected", get(protected));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Now a missing header returns:

{"error":"missing Authorization header"}

with status 401, and the body is valid JSON. This pattern is recommended for any public API.

Parsing Tokens Beyond the Prefix

Extracting the raw token string is only the first step. In a real application you must validate the token. That validation could involve looking it up in a database, checking a signature (for JWT), or calling an external identity provider. The parsing extractor should remain focused on extracting the token; the validation can happen in a separate middleware or inside the handler. However, if you want the extractor to fail early, you can perform a basic check inside from_request_parts.

For example, you might reject tokens shorter than 20 characters. First add a variant to the error enum (TokenTooShort returning 401 with "token is too short"), then check the length inside from_request_parts:

if token.len() < 20 {
    return Err(AuthError::TokenTooShort);
}

Or you could call verify_jwt(token) and return a custom error on failure. The key is to keep the parsing logic separate from the business logic that uses the token. A well‑designed extractor returns a Token type that the handler can trust has already passed syntactic validation, and possibly even semantic validation if you choose to do it there.

Don't Overload the Extractor with Business Logic:

While it is tempting to validate the token inside the extractor and return a fully hydrated User, that couples the parsing of the header with database lookups and session management. For small projects that is fine, but as the API grows, you may want to separate authentication from authorization. The extractor should at minimum ensure the header is present and correctly formatted; deeper checks can be a middleware or a separate service.

Complete Example Application

Let's put the Bearer parsing extractor into a small but complete Axum application with a few routes: one public route, one protected route, and one optional-authentication route. This shows how all the pieces fit together in a realistic main.rs.

src/main.rs
use axum::{
    extract::{FromRequestParts, OptionalFromRequestParts},
    http::{header::AUTHORIZATION, request::Parts, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
pub struct AuthUser {
    pub token: String,
}
pub enum AuthError {
    MissingHeader,
    InvalidScheme,
    InvalidUtf8,
    MissingToken,
}
impl IntoResponse for AuthError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AuthError::MissingHeader => (StatusCode::UNAUTHORIZED, "missing Authorization header"),
            AuthError::InvalidScheme => (StatusCode::UNAUTHORIZED, "only Bearer tokens are accepted"),
            AuthError::InvalidUtf8 => (StatusCode::BAD_REQUEST, "header contains invalid characters"),
            AuthError::MissingToken => (StatusCode::UNAUTHORIZED, "Bearer token is empty"),
        };
        (status, message).into_response()
    }
}
impl<S> FromRequestParts<S> for AuthUser
where
    S: Send + Sync,
{
    type Rejection = AuthError;
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let auth_header = parts
            .headers
            .get(AUTHORIZATION)
            .ok_or(AuthError::MissingHeader)?;
        let auth_str = auth_header
            .to_str()
            .map_err(|_| AuthError::InvalidUtf8)?;
        let (scheme, token) = auth_str
            .split_once(char::is_whitespace)
            .ok_or(AuthError::InvalidScheme)?;
        if !scheme.eq_ignore_ascii_case("Bearer") {
            return Err(AuthError::InvalidScheme);
        }
        let token = token.trim();
        if token.is_empty() {
            return Err(AuthError::MissingToken);
        }
        Ok(AuthUser {
            token: token.to_string(),
        })
    }
}
impl<S> OptionalFromRequestParts<S> for AuthUser
where
    S: Send + Sync,
{
    type Rejection = AuthError;
    async fn from_request_parts(
        parts: &mut Parts,
        state: &S,
    ) -> Result<Option<Self>, Self::Rejection> {
        if parts.headers.contains_key(AUTHORIZATION) {
            match <Self as FromRequestParts<S>>::from_request_parts(parts, state).await {
                Ok(user) => Ok(Some(user)),
                Err(err) => Err(err),
            }
        } else {
            Ok(None)
        }
    }
}
async fn public() -> &'static str {
    "This is a public route."
}
async fn protected(user: AuthUser) -> String {
    format!("You accessed a protected route with token {}", user.token)
}
async fn maybe(user: Option<AuthUser>) -> String {
    match user {
        Some(u) => format!("Authenticated with token {}", u.token),
        None => "Anonymous access".to_string(),
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(public))
        .route("/protected", get(protected))
        .route("/maybe", get(maybe));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Test the three routes:

  1. curl http://127.0.0.1:3000/ → public message.
  2. curl http://127.0.0.1:3000/protected → 401 with missing Authorization header.
  3. curl -H "Authorization: Bearer abc123" http://127.0.0.1:3000/protected → success with token.
  4. curl http://127.0.0.1:3000/maybe → Anonymous access.
  5. curl -H "Authorization: Bearer abc123" http://127.0.0.1:3000/maybe → Authenticated with token abc123.
  6. curl -H "Authorization: Bearer" http://127.0.0.1:3000/protected → 401 with {"error":"only Bearer tokens are accepted"}. There is no whitespace in the header, so split_once returns None and the InvalidScheme branch runs; the MissingToken branch only fires when whitespace is present but the token part is empty after trimming.

This single file demonstrates all the core concepts: extracting the header, parsing the scheme, handling errors, optional authentication, and using the extractor in multiple handlers.

Common Mistakes and Misconceptions

When implementing authorization parsing, beginners often run into a few predictable problems.

1. Forgetting to trim whitespace
If you use split_once(" ") and the client sends multiple spaces, the token part may include extra spaces or be empty. Always trim the credential part after splitting on whitespace.

2. Using case‑sensitive scheme checks
HTTP authentication schemes are case‑insensitive. If you only accept Bearer exactly, clients sending bearer will be rejected even though the RFC says it should work. Use eq_ignore_ascii_case.

3. Attempting to consume the body
Remember that FromRequestParts cannot access the request body. If your extractor needs the body, you must implement FromRequest instead. However, Authorization parsing only needs headers, so FromRequestParts is correct.

4. Forgetting IntoResponse on a custom rejection type
The rejection type must implement IntoResponse. If you define a custom error enum, you must also implement IntoResponse for it or the code will not compile.

5. Assuming Option<AuthUser> never rejects
As noted earlier, Option only suppresses the "missing" case via OptionalFromRequestParts. If the header exists but is malformed, the request is still rejected. This surprises many beginners.

Never Trust the Client:

No matter how carefully you parse the Authorization header, the credentials may still be invalid, expired, or forged. Parsing only checks the structure and scheme; it does not verify the token's authenticity or the user's identity. Always validate the token against a trusted source before granting access to sensitive resources.

Summary

Authorization parsing in Axum is about taking a raw Authorization header and turning it into a typed value your handlers can use. You can read the header with HeaderMap, use TypedHeader from axum-extra, or manually split and decode the value. For Bearer tokens, the pattern is scheme + token; for Basic, it is scheme + base64(username:password). A custom extractor that implements FromRequestParts can perform this parsing once and be reused across many handlers. When the header is absent or malformed, you return a rejection that Axum converts into an HTTP error response. By also implementing OptionalFromRequestParts, you can let the extractor return None for anonymous requests while still rejecting invalid credentials.

The single most important takeaway: separate parsing from validation. Parsing ensures the header has the right shape and extracts the credential. Validation (checking the token against a database, verifying a JWT signature, matching a password) belongs in a different layer. Keeping these concerns separate makes your authentication code easier to test, maintain, and reason about. With the extractor patterns shown here, you can now build secure endpoints that accept Bearer tokens, Basic credentials, or both, while giving your handlers clean, typed access to the authenticated principal.