Authentication with Axum
Use case
You need to protect routes: basic auth (username/password in header) or bearer tokens (e.g. JWT in Authorization). In Axum you use extractors to read headers and validate; rejected requests return 401 Unauthorized.
In C#: Like [Authorize], JWT bearer middleware, or custom middleware that checks headers. In Rust, you typically use an extractor that returns an error (e.g. 401) when auth fails.
Basic Auth
The Authorization: Basic <base64> header contains base64-encoded username:password. Parse the header, decode base64, split on :, and compare to expected credentials. Use axum_extra::TypedHeader or axum::http::HeaderMap to read headers.
use axum::http::HeaderMap;
use base64::Engine; // base64 crate
fn check_basic(headers: &HeaderMap) -> Option<()> {
let auth = headers.get("authorization")?.to_str().ok()?;
let (_, encoded) = auth.split_once(" ")?;
let decoded = base64::engine::general_purpose::STANDARD.decode(encoded).ok()?;
let s = String::from_utf8(decoded).ok()?;
let (user, pass) = s.split_once(':')?;
if user == "admin" && pass == "secret" { Some(()) } else { None }
}In C#: Like parsing Authorization and validating against stored credentials; similar logic in middleware or a filter.
Bearer token (e.g. JWT)
Read Authorization: Bearer <token>, extract the token, and validate it (e.g. verify signature and expiry with a JWT library). If invalid, return 401. Use a custom extractor or a layer that validates and injects the user.
In C#: Like JWT bearer middleware that validates the token and sets the user. In Rust you'd use jsonwebtoken or similar and an extractor.
Custom extractor
Implement FromRequestParts for your auth type. In from_request_parts, read headers, validate, and return Err(StatusCode::UNAUTHORIZED) or a typed error when auth fails. Handlers that take your type will only run when auth succeeds.
In C#: Like a filter or middleware that short-circuits with 401; in Axum the extractor does the check before the handler runs.
Key takeaway
Read Authorization from headers; for Basic decode base64 and compare credentials; for Bearer validate the token. Use a custom extractor or a function that returns Result/Option and map failure to 401. For JWT use a crate like jsonwebtoken.