axum_jwt_auth/
lib.rs

1//! A Rust library for JWT authentication with support for both local keys and remote JWKS (JSON Web Key Sets).
2//!
3//! This crate provides a flexible JWT authentication system that can:
4//! - Validate tokens using local RSA/HMAC keys
5//! - Automatically fetch and cache remote JWKS endpoints
6//! - Integrate seamlessly with the Axum web framework
7//! - Handle token validation with configurable options
8//!
9//! It builds on top of the `jsonwebtoken` crate to provide higher-level authentication primitives
10//! while maintaining full compatibility with standard JWT implementations.
11//!
12//! # Example
13//!
14//! For a full example, see the [examples](https://github.com/cmackenzie1/axum-jwt-auth/blob/main/examples).
15
16mod axum;
17mod local;
18mod remote;
19
20use std::sync::Arc;
21
22use async_trait::async_trait;
23use jsonwebtoken::TokenData;
24use serde::de::DeserializeOwned;
25use thiserror::Error;
26
27pub use crate::axum::{AuthError, Claims, JwtDecoderState};
28pub use crate::local::LocalDecoder;
29pub use crate::remote::{
30    RemoteJwksDecoder, RemoteJwksDecoderBuilder, RemoteJwksDecoderConfig,
31    RemoteJwksDecoderConfigBuilder,
32};
33
34#[derive(Debug, thiserror::Error)]
35pub enum Error {
36    #[error("JWT key not found (kid: {0:?})")]
37    KeyNotFound(Option<String>),
38
39    #[error("Configuration error: {0}")]
40    Configuration(String),
41
42    #[error("JWT error: {0}")]
43    Jwt(#[from] jsonwebtoken::errors::Error),
44
45    #[error("HTTP request error: {0}")]
46    Reqwest(#[from] reqwest::Error),
47
48    #[error("JWKS refresh failed after {retry_count} attempts: {message}")]
49    JwksRefresh {
50        message: String,
51        retry_count: usize,
52        #[source]
53        source: Option<Box<dyn std::error::Error + Send + Sync>>,
54    },
55}
56
57/// A generic trait for decoding JWT tokens.
58///
59/// This trait is implemented for both `LocalDecoder` and `RemoteJwksDecoder`
60#[async_trait]
61pub trait JwtDecoder<T>
62where
63    T: for<'de> DeserializeOwned,
64{
65    async fn decode(&self, token: &str) -> Result<TokenData<T>, Error>;
66}
67
68/// A type alias for a decoder that can be used as a state in an Axum application.
69pub type Decoder<T> = Arc<dyn JwtDecoder<T> + Send + Sync>;