Crate axum_jwt_auth

Crate axum_jwt_auth 

Source
Expand description

A Rust library for JWT authentication with support for both local keys and remote JWKS (JSON Web Key Sets).

This crate provides a flexible JWT authentication system that can:

  • Validate tokens using local RSA/HMAC keys
  • Automatically fetch and cache remote JWKS endpoints
  • Integrate seamlessly with the Axum web framework
  • Handle token validation with configurable options
  • Extract tokens from multiple sources (headers or cookies)

It builds on top of the jsonwebtoken crate to provide higher-level authentication primitives while maintaining full compatibility with standard JWT implementations.

§Quick Start

§Using Bearer Tokens (Default)

use std::sync::Arc;
use axum::{Router, routing::get, Json, extract::FromRef};
use axum_jwt_auth::{Claims, Decoder, LocalDecoder};
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize)]
struct MyClaims {
    sub: String,
    exp: usize,
}

#[derive(Clone, FromRef)]
struct AppState {
    decoder: Decoder<MyClaims>,
}

async fn protected_handler(user: Claims<MyClaims>) -> Json<MyClaims> {
    Json(user.claims)
}

let decoder = LocalDecoder::builder()
    .keys(keys)
    .validation(validation)
    .build()
    .unwrap();

let state = AppState {
    decoder: Arc::new(decoder),
};

let app = Router::new()
    .route("/protected", get(protected_handler))
    .with_state(state);

§Custom Token Extractors

Use macros to easily define custom extractors:

use axum_jwt_auth::{define_header_extractor, define_cookie_extractor};
use axum_jwt_auth::{Claims, HeaderTokenExtractor, CookieTokenExtractor};

// Define custom extractors
define_header_extractor!(XAuthToken, "x-auth-token");
define_cookie_extractor!(AuthCookie, "auth_token");

// Use in handlers
async fn header_handler(user: Claims<MyClaims, HeaderTokenExtractor<XAuthToken>>) {
    // Token extracted from "x-auth-token" header
}

async fn cookie_handler(user: Claims<MyClaims, CookieTokenExtractor<AuthCookie>>) {
    // Token extracted from "auth_token" cookie
}

§Examples

For full examples, see the examples directory.

Macros§

define_cookie_extractor
Creates a custom cookie token extractor with the given name and cookie value.
define_header_extractor
Creates a custom header token extractor with the given name and header value.

Structs§

BearerTokenExtractor
Extracts JWT tokens from the Authorization: Bearer <token> header.
Claims
Axum extractor for validated JWT claims.
CookieTokenExtractor
Extracts JWT tokens from an HTTP cookie.
HeaderTokenExtractor
Extracts JWT tokens from a custom HTTP header.
LocalDecoder
JWT decoder that validates tokens using locally stored keys.
RemoteJwksDecoder
JWT decoder that fetches and caches keys from a remote JWKS endpoint.
RemoteJwksDecoderBuilder
Builder for RemoteJwksDecoder.
RemoteJwksDecoderConfig
Configuration for remote JWKS fetching and caching behavior.
RemoteJwksDecoderConfigBuilder
Builder for RemoteJwksDecoderConfig.

Enums§

AuthError
Authentication errors that can occur during JWT extraction and validation.
Error
Errors that can occur during JWT decoding and validation.

Traits§

ExtractorConfig
Provides configuration values for token extractors.
JwtDecoder
Trait for decoding and validating JWT tokens.
TokenExtractor
Trait for extracting JWT tokens from HTTP requests.

Type Aliases§

Decoder
Type alias for a thread-safe, trait-object decoder suitable for Axum state.