| Crates.io | auth-middleware-pkg |
| lib.rs | auth-middleware-pkg |
| version | 0.1.0 |
| created_at | 2025-11-08 20:17:03.969405+00 |
| updated_at | 2025-11-08 20:17:03.969405+00 |
| description | JWT authentication middleware for Axum with token validation and role-based access control |
| homepage | |
| repository | https://github.com/crypto-priest/auth-middleware |
| max_upload_size | |
| id | 1923243 |
| size | 47,331 |
JWT authentication middleware for Axum applications with built-in token validation and role-based access control support.
[dependencies]
auth-middleware-pkg = "0.1.0"
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"
}
The middleware accepts tokens in two formats:
Authorization: Bearer <token>Authorization: <token>pub struct Claims {
pub sub: String, // Subject (user ID/username)
pub exp: usize, // Expiration time (Unix timestamp)
pub role: String, // User role
}
All errors return JSON responses:
{
"message": "Error description"
}
Common error scenarios:
Licensed under either of:
at your option.