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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Implementing FromRequestParts lets a handler receive a fully authenticated value as an argument, keeping auth logic out of the handler.
- 2A dedicated error enum with IntoResponse maps each failure to a distinct status code and JSON body in one place.
- 3Bounding on FromRef<S> for PgPool lets the extractor pull shared state without hard-coding a concrete app-state type.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-custom-api-key-extractor-in-axum-explained-rust-3e14/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.