Authorization Header in Axum

Learn how to extract and work with the Authorization header in Axum handlers, covering raw header access, typed bearer tokens, basic authentication, and custom extractors.

The Authorization header is how HTTP requests carry credentials to prove who the client is. When you log into a website or call an API with a token, that token usually travels inside this header. In Axum, you can read this header in several ways, from raw string access to strongly typed parsing of common authentication schemes. This page walks through each approach, starting from the absolute basics and building up to a reusable custom extractor.

Reading the Raw Authorization Header

The simplest way to get the Authorization header is to treat it like any other header. Request headers.get with a header name constant, then convert the value into a string.

Here is a minimal handler that returns the raw value of the Authorization header:

use axum::{http::HeaderMap, http::header::AUTHORIZATION, routing::get, Router};
async fn show_auth_header(headers: HeaderMap) -> String {
    match headers.get(AUTHORIZATION) {
        Some(value) => format!("Authorization header value: {:?}", value),
        None => "No Authorization header sent".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 this and send a request with an Authorization header using curl:

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

The response body will be something like:

Authorization header value: "Bearer my-secret-token"

This approach is fine when you need the exact raw string, maybe to log it or pass it to an external service. But for real authentication logic, you almost always need to understand the structure inside the header. The Authorization header has a scheme (like Bearer or Basic) followed by the actual credential. A raw string forces you to split and validate that manually, which is error‑prone. That is why Axum offers typed extraction via the axum-extra crate.

Header names are case-insensitive:

HTTP header names are case-insensitive. Using the AUTHORIZATION constant from axum::http::header avoids accidental typos and makes your intent clear. You could also write headers.get("authorization"), but the constant is safer.

Typed Authorization with axum-extra

The axum-extra crate provides a TypedHeader extractor that understands the headers crate's typed header types. For Authorization, you get Authorization<Bearer> and Authorization<Basic> out of the box. These parse the header according to the scheme and give you a safe, structured value.

To use this, add axum-extra with the typed-header feature to your Cargo.toml:

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

Now you can write a handler that extracts a bearer token directly:

use axum::{routing::get, Router};
use axum_extra::TypedHeader;
use axum_extra::headers::{authorization::Bearer, Authorization};
async fn show_bearer_token(TypedHeader(auth): TypedHeader<Authorization<Bearer>>) -> String {
    format!("Bearer token: {}", auth.token())
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(show_bearer_token));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

If the request includes Authorization: Bearer abc123, the handler returns:

Bearer token: abc123

Here is what happens when you send the wrong scheme, like Basic:

curl -H "Authorization: Basic dXNlcjpwYXNz" http://127.0.0.1:3000/

The extraction fails because the typed header expected Bearer but got Basic. Axum will return a 400 Bad Request response with an error message, and your handler will not run.

This is the power of TypedHeader: it validates the header before your function body executes. You can trust that auth.token() contains a valid bearer token string.

Typed extraction handles parsing for you:

If you see a successful response with the token, everything is working correctly. The Authorization<Bearer> type validates the scheme, extracts the token part, and gives you an immutable reference to the token string. You never have to manually split on a space.

Extracting Basic Authentication Credentials

The Basic scheme is older but still common. The Authorization header value looks like Basic base64(username:password). The Authorization<Basic> type decodes the Base64 and exposes the username and password as separate fields.

Add a handler that accepts Authorization<Basic>:

use axum::{routing::get, Router};
use axum_extra::TypedHeader;
use axum_extra::headers::{authorization::Basic, Authorization};
async fn show_basic_credentials(
    TypedHeader(auth): TypedHeader<Authorization<Basic>>,
) -> String {
    let username = auth.username();
    // Password is a plain &str; Basic auth can have an empty password, which is just ""
    let password = auth.password();
    format!("Username: {}, Password: {}", username, password)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(show_basic_credentials));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Test it with a correctly encoded header:

# "user:pass" base64 encoded is dXNlcjpwYXNz
curl -H "Authorization: Basic dXNlcjpwYXNz" http://127.0.0.1:3000/

The response:

Username: user, Password: pass

Notice that password() returns a plain &str, not an Option. The Basic scheme technically allows a username with no password (user:); the typed extractor represents that as an empty string.

Basic auth sends credentials in plaintext when not using HTTPS:

The Base64 encoding in Basic authentication is not encryption. Anyone who intercepts the request can decode it and see the username and password. Always use Basic authentication over HTTPS in production, or prefer Bearer tokens with proper expiration.

Choosing Between Basic and Bearer with Tabs

You often need to support one scheme or the other, not both in the same handler. The examples below show the same endpoint implemented for each scheme. Choose the tab that matches your application's authentication method.

use axum::{routing::get, Router};
use axum_extra::TypedHeader;
use axum_extra::headers::{authorization::Bearer, Authorization};
async fn protected(TypedHeader(auth): TypedHeader<Authorization<Bearer>>) -> String {
    format!("Access granted for token: {}", auth.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();
}

Both examples rely on TypedHeader and the Authorization type. The only difference is the generic parameter: Bearer or Basic. This keeps your authentication logic consistent and type-safe.

Making Authorization Optional

Sometimes an endpoint works for both authenticated and anonymous users. For example, a public feed that shows extra content if the user is logged in. In Axum, you can wrap the typed header in Option to make extraction optional.

use axum::{routing::get, Router};
use axum_extra::TypedHeader;
use axum_extra::headers::{authorization::Bearer, Authorization};
async fn optional_auth(
    auth: Option<TypedHeader<Authorization<Bearer>>>,
) -> String {
    match auth {
        Some(TypedHeader(auth)) => format!("Authenticated with token: {}", auth.token()),
        None => "Anonymous access".to_string(),
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(optional_auth));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Now send a request without the header:

curl http://127.0.0.1:3000/

The response is Anonymous access. If you add the header, it returns the authenticated message.

Only presence is optional, not validity:

Wrapping in Option only handles the case where the header is missing. If the header is present but malformed (wrong scheme, invalid format), extraction still fails and the request is rejected. The Option does not swallow parse errors.

Handling Extraction Errors with Result

By default, a failed extraction returns a generic error response. To customize what the client sees, use Result<TypedHeader<...>, TypedHeaderRejection> as the handler parameter type. This gives you the exact rejection reason.

Here is an example that distinguishes between a missing header and a wrong scheme:

use axum::{http::StatusCode, routing::get, Router};
use axum_extra::{TypedHeader, headers::{authorization::Bearer, Authorization}};
use axum_extra::typed_header::TypedHeaderRejection;
async fn protected(
    result: Result<TypedHeader<Authorization<Bearer>>, TypedHeaderRejection>,
) -> Result<String, (StatusCode, String)> {
    match result {
        Ok(TypedHeader(auth)) => Ok(format!("Token: {}", auth.token())),
        Err(rejection) => {
            let message = match rejection.reason() {
                axum_extra::typed_header::TypedHeaderRejectionReason::Missing => {
                    "Missing Authorization header".to_string()
                }
                axum_extra::typed_header::TypedHeaderRejectionReason::Error(_) => {
                    "Invalid Authorization header".to_string()
                }
                // The enum is #[non_exhaustive], so a catch-all arm is required
                _ => "Invalid Authorization header".to_string(),
            };
            Err((StatusCode::BAD_REQUEST, message))
        }
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(protected));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

The TypedHeaderRejection has a reason() method that returns an enum with two variants: Missing and Error. (The name() method returns something else: the name of the header that failed, as a &HeaderName.) You can use reason() to build a clear error response. Note that TypedHeaderRejectionReason is behind the typed-header feature and may require importing it from axum_extra::typed_header.

Error matching may change between versions:

The exact rejection types and enums in axum-extra can change in future releases. If you rely on pattern matching like this, be prepared to update your code when you upgrade dependencies. For maximum stability, a custom extractor (shown next) gives you full control over rejection types.

Building a Custom Authorization Extractor

If you need a fully customized rejection type or want to encapsulate token validation logic (like checking a database), a custom extractor is the cleanest solution. You implement FromRequestParts for your own type, read the Authorization header manually, parse it, and return either the extracted value or your own error type.

Here is a complete example that extracts a bearer token and returns a custom AuthError on failure:

use axum::{
    extract::FromRequestParts,
    http::request::Parts,
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
// Custom error type
#[derive(Debug)]
enum AuthError {
    MissingHeader,
    InvalidScheme,
    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, "Authorization scheme must be Bearer"),
            AuthError::MissingToken => (StatusCode::UNAUTHORIZED, "Bearer token is empty"),
        };
        (status, message).into_response()
    }
}
// Custom extractor
struct BearerToken(String);
impl<S> FromRequestParts<S> for BearerToken
where
    S: Send + Sync,
{
    type Rejection = AuthError;
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let header_value = parts
            .headers
            .get(axum::http::header::AUTHORIZATION)
            .ok_or(AuthError::MissingHeader)?;
        let header_str = header_value
            .to_str()
            .map_err(|_| AuthError::InvalidScheme)?;
        let mut parts_iter = header_str.splitn(2, ' ');
        let scheme = parts_iter.next().ok_or(AuthError::InvalidScheme)?;
        if scheme != "Bearer" {
            return Err(AuthError::InvalidScheme);
        }
        let token = parts_iter.next().ok_or(AuthError::MissingToken)?;
        if token.is_empty() {
            return Err(AuthError::MissingToken);
        }
        Ok(BearerToken(token.to_string()))
    }
}
async fn handler(BearerToken(token): BearerToken) -> String {
    format!("Authenticated with token: {}", token)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

This extractor does exactly what TypedHeader<Authorization<Bearer>> does internally, but you control every error message and status code. You could extend it to check a database of valid tokens or add caching. Because it implements FromRequestParts, it does not consume the body, so it can be used alongside other extractors that also implement FromRequestParts.

Be careful with splitn and whitespace:

The Authorization header syntax is scheme token, with exactly one space. Using splitn(2, ' ') handles that correctly. If the token itself contains spaces (which it should not for Bearer), you would need a different parsing strategy.

Common Mistakes and How to Avoid Them

Forgetting the scheme name

A frequent mistake is reading the header value and trying to use it directly as a token, forgetting that it starts with Bearer or Basic . Always parse the scheme first or use a typed extractor that does it for you.

Using the wrong header constant

Some developers write headers.get("Authorization") and later change the case or add a typo. Use axum::http::header::AUTHORIZATION to prevent that.

Comparing tokens with ==

When checking if a token matches an expected value, using == can leak timing information. In security‑sensitive code, use a constant‑time comparison crate like subtle or constant_time_eq. This is outside Axum but important for real authentication.

Not logging or storing credentials safely

Never log the full Authorization header. If you must log, redact the token or log only the scheme. Treat the header value as a secret.

Assuming Basic auth is encrypted

As mentioned, Basic authentication sends credentials in a reversible encoding. Only use it over HTTPS.

Summary and Decision Framework

You now have several ways to work with the Authorization header in Axum:

  • Use raw HeaderMap when you need the original string or want to handle parsing yourself.
  • Use TypedHeader<Authorization<Bearer>> or Authorization<Basic> for standard schemes with minimal code.
  • Use Option<TypedHeader<...>> for endpoints that allow anonymous access.
  • Use Result<TypedHeader<...>, TypedHeaderRejection> to customize error responses for a single handler.
  • Build a custom extractor implementing FromRequestParts when you need reusable validation logic, custom error types, or integration with a user database.

The key insight is that typed extraction moves validation earlier in the request lifecycle. Your handler code can assume the token is present and correctly formatted, which simplifies the business logic. For most projects, starting with TypedHeader and falling back to a custom extractor when needed is the most maintainable path. Understanding this pattern unlocks building authentication middleware and protected routes on top of Axum.