auth-middleware-pkg

Crates.ioauth-middleware-pkg
lib.rsauth-middleware-pkg
version0.1.0
created_at2025-11-08 20:17:03.969405+00
updated_at2025-11-08 20:17:03.969405+00
descriptionJWT authentication middleware for Axum with token validation and role-based access control
homepage
repositoryhttps://github.com/crypto-priest/auth-middleware
max_upload_size
id1923243
size47,331
Mahavir Ganapati Dash (crypto-priest)

documentation

README

Auth Middleware

JWT authentication middleware for Axum applications with built-in token validation and role-based access control support.

Features

  • 🔐 JWT token validation
  • 🛡️ Middleware integration with Axum
  • 🎫 Support for Bearer and direct token formats
  • ⚡ Configurable secret keys
  • 👤 Claims extraction in handlers
  • 🚀 Zero-boilerplate authentication
  • 📦 Type-safe and ergonomic API

Installation

[dependencies]
auth-middleware-pkg = "0.1.0"

Quick Start

use axum::{Router, routing::get, middleware};
use auth_middleware::{jwt_auth_middleware, JwtConfig};

#[tokio::main]
async fn main() {
    // Configure JWT
    let jwt_config = JwtConfig::new("your-secret-key".to_string());

    // Protected routes
    let protected_routes = Router::new()
        .route("/protected", get(protected_handler))
        .layer(middleware::from_fn(jwt_auth_middleware))
        .layer(axum::Extension(jwt_config));

    // Public routes
    let app = Router::new()
        .route("/public", get(public_handler))
        .merge(protected_routes);

    // Run server
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();

    axum::serve(listener, app).await.unwrap();
}

// Access claims in your handler
async fn protected_handler(
    claims: auth_middleware::Claims,
) -> String {
    format!("Hello, {}! Your role: {}", claims.sub, claims.role)
}

async fn public_handler() -> &'static str {
    "Public endpoint - no auth required"
}

Token Format

The middleware accepts tokens in two formats:

  1. Bearer format: Authorization: Bearer <token>
  2. Direct format: Authorization: <token>

Claims Structure

pub struct Claims {
    pub sub: String,   // Subject (user ID/username)
    pub exp: usize,    // Expiration time (Unix timestamp)
    pub role: String,  // User role
}

Error Responses

All errors return JSON responses:

{
  "message": "Error description"
}

Common error scenarios:

  • Missing authorization header → 401 Unauthorized
  • Invalid token format → 401 Unauthorized
  • Expired token → 401 Unauthorized
  • Invalid signature → 401 Unauthorized

License

Licensed under either of:

at your option.

Commit count: 0

cargo fmt