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.
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));
}
}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 charactersHandlers 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.
Related questions#
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#
- axum,
FromRequestParts: https://docs.rs/axum/0.8.9/axum/extract/trait.FromRequestParts.html (read 2026-12-05)