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
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
rust
use std::cmp::Ordering; pub struct PrefixIndex { entries: Vec<String>,
Prefix search with binary partitioning in Rust
binary-search
sorting
case-insensitive
Intermediate
7 steps
typescript
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { catchError, filter, take, switchMap } from 'rxjs/operators';
Refreshing auth tokens in an Angular interceptor
http-interceptor
token-refresh
rxjs
Advanced
8 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 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.