rust 71 lines · 8 steps

A custom API-key extractor in Axum

Turning an Authorization header into an authenticated ApiClient by implementing Axum's FromRequestParts trait.

Explained by highlit
1use axum::{
2 extract::{FromRef, FromRequestParts},
3 http::{request::Parts, StatusCode},
4 response::{IntoResponse, Response},
5 Json,
6};
7use serde_json::json;
8use sqlx::PgPool;
9 
10pub struct ApiClient {
11 pub id: i64,
12 pub name: String,
13 pub scopes: Vec<String>,
14}
15 
16pub enum AuthError {
17 Missing,
18 Malformed,
19 Invalid,
20 Internal,
21}
22 
23impl IntoResponse for AuthError {
24 fn into_response(self) -> Response {
25 let (status, message) = match self {
26 AuthError::Missing => (StatusCode::UNAUTHORIZED, "missing api key"),
27 AuthError::Malformed => (StatusCode::BAD_REQUEST, "malformed authorization header"),
28 AuthError::Invalid => (StatusCode::UNAUTHORIZED, "invalid api key"),
29 AuthError::Internal => (StatusCode::INTERNAL_SERVER_ERROR, "internal error"),
30 };
31 (status, Json(json!({ "error": message }))).into_response()
32 }
33}
34 
35impl<S> FromRequestParts<S> for ApiClient
36where
37 PgPool: FromRef<S>,
38 S: Send + Sync,
39{
40 type Rejection = AuthError;
41 
42 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
43 let header = parts
44 .headers
45 .get("authorization")
46 .ok_or(AuthError::Missing)?
47 .to_str()
48 .map_err(|_| AuthError::Malformed)?;
49 
50 let raw = header.strip_prefix("Bearer ").ok_or(AuthError::Malformed)?;
51 let hash = blake3::hash(raw.as_bytes()).to_hex().to_string();
52 
53 let pool = PgPool::from_ref(state);
54 let client = sqlx::query_as!(
55 ApiClient,
56 r#"SELECT id, name, scopes FROM api_clients WHERE key_hash = $1 AND revoked_at IS NULL"#,
57 hash,
58 )
59 .fetch_optional(&pool)
60 .await
61 .map_err(|_| AuthError::Internal)?
62 .ok_or(AuthError::Invalid)?;
63 
64 sqlx::query!("UPDATE api_clients SET last_used_at = now() WHERE id = $1", client.id)
65 .execute(&pool)
66 .await
67 .map_err(|_| AuthError::Internal)?;
68 
69 Ok(client)
70 }
71}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Implementing FromRequestParts lets a handler receive a fully authenticated value as an argument, keeping auth logic out of the handler.
  2. 2A dedicated error enum with IntoResponse maps each failure to a distinct status code and JSON body in one place.
  3. 3Bounding on FromRef<S> for PgPool lets the extractor pull shared state without hard-coding a concrete app-state type.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A custom API-key extractor in Axum — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code