axum-impl-auth-jwt
Axum JWT Authentication
Overview
Stateless JWT authentication in Axum is built from six pieces, mirroring the official
tokio-rs/axum examples/jwt crate: a Claims struct, a Keys struct holding an
EncodingKey and a DecodingKey, an AuthError enum that implements IntoResponse,
a FromRequestParts extractor for Claims, a protected handler, and a login handler
that issues a token.
The core mechanism: Claims implements FromRequestParts, so any handler that takes
claims: Claims as an argument is automatically protected. A missing, malformed, or
expired token makes the extractor return Err(AuthError::InvalidToken), which becomes
the HTTP response, and the handler body never runs. Authentication is enforced by the
type system, not by a guard call inside the handler.
Two rules dominate correct JWT code: