FAQ - Help and questions

How do I write a custom extractor in axum, for example for a bearer token?

#axum#extractors#authentication#httppublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Implement FromRequestParts for your type. Its async function receives the request parts and the state and returns the value or a rejection that is also a response. Handlers that list the type as an argument are then protected, and the check lives in one place.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

An extractor is a type that axum can build from a request. For anything that does not need the body (headers, cookies, the client address) implement FromRequestParts; for body-based types implement FromRequest. In axum 0.8 the trait uses plain async fn, so no async_trait attribute is needed.

src/main.rsrust
use axum::{
    body::{to_bytes, Body},
    extract::FromRequestParts,
    http::{header::AUTHORIZATION, request::Parts, Request, StatusCode},
    routing::get,
    Router,
};
use tower::ServiceExt;

struct BearerToken(String);

impl<S: Send + Sync> FromRequestParts<S> for BearerToken {
    type Rejection = (StatusCode, &'static str);

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let value = parts.headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok());
        match value.and_then(|v| v.strip_prefix("Bearer ")) {
            Some(token) if !token.is_empty() => Ok(BearerToken(token.to_string())),
            _ => Err((StatusCode::UNAUTHORIZED, "send an Authorization: Bearer <token> header")),
        }
    }
}

async fn me(BearerToken(token): BearerToken) -> String { format!("token of {} characters", token.len()) }

#[tokio::main]
async fn main() {
    let app = Router::new().route("/me", get(me));
    for header in [None, Some("Basic abc"), Some("Bearer abc123")] {
        let mut b = Request::get("/me");
        if let Some(h) = header { b = b.header(AUTHORIZATION, h); }
        let res = app.clone().oneshot(b.body(Body::empty()).unwrap()).await.unwrap();
        let status = res.status().as_u16();
        let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
        println!("{header:?} -> {status} {}", String::from_utf8_lossy(&body));
    }
}
text
None -> 401 send an Authorization: Bearer <token> header
Some("Basic abc") -> 401 send an Authorization: Bearer <token> header
Some("Bearer abc123") -> 200 token of 6 characters

Handlers that take BearerToken are only reached when the header has the right shape; otherwise the Rejection (here a status and a text) is sent. Adding the argument to any handler protects that handler, and removing it removes the check.

This extractor checks only the format of the header. Whether the token is genuine (found in a table, or a valid signature) is a second step that belongs in the extractor too, using a State value.

Common mistakes#

  • Treating "a header is present" as "the user is logged in".
  • Returning detailed reasons for token failures to the client. One message for every failure is safer.

Can an extractor use the application state?#

Yes: the _state: &S argument is the application state, so a database lookup of the token can be added there. The extractor documentation describes the details.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet