# 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
```toml
[dependencies]
auth-middleware-pkg = "0.1.0"
```
## Quick Start
```rust
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
```rust
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:
```json
{
"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:
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE))
- MIT license ([LICENSE-MIT](LICENSE-MIT))
at your option.