Axum Firebase Middleware
A production-ready Firebase JWT authentication middleware for Axum web applications. This crate provides secure token validation with automatic public key caching, comprehensive error handling, and built-in security features.
Features
- Secure JWT validation with Firebase-specific claim verification
- Automatic public key caching with configurable expiration and key rotation
- Production-ready error handling with detailed, actionable error types
- Security hardening including token length limits, timing validation, and DoS protection
- Retry logic with exponential backoff for robust key fetching
- Comprehensive logging for monitoring and debugging
- Zero-copy where possible for optimal performance
Quick Start
Add this to your Cargo.toml:
[]
= "0.1.0"
= "0.8"
= { = "1.0", = ["full"] }
Basic usage:
use ;
use ;
use json;
// Your protected handler
async
// Public handler (no authentication required)
async
async
Usage
1. Get Firebase Project ID
Get your Firebase project ID from the Firebase Console:
- Go to Firebase Console
- Select your project
- Click on Project Settings (gear icon)
- Copy the Project ID
2. Client-side Token Generation
On your client (web, mobile app), authenticate users and get ID tokens:
// Web example using Firebase SDK
import from 'firebase/auth';
const auth = ;
const userCredential = await ;
const idToken = await ;
// Use this token in Authorization header
;
3. Server-side Validation
The middleware automatically validates tokens and provides claims:
async
Configuration Options
Custom Cache Duration
let config = new?
.with_cache_duration?; // Cache for 30 minutes
Custom Token Age Limits
let config = new?
.with_max_token_age; // 12 hours max
Error Handling
The middleware returns appropriate HTTP status codes:
401 Unauthorized: Invalid, expired, or malformed tokens503 Service Unavailable: Firebase key service unavailable429 Too Many Requests: Rate limiting (if implemented)413 Payload Too Large: Request body too large500 Internal Server Error: Configuration errors
Custom error handling:
use FirebaseAuthError;
match validate_firebase_token.await
Security Features
- Token length limits prevent DoS attacks
- Timing validation prevents replay attacks with old tokens
- Algorithm validation ensures only RS256 is accepted
- Claim validation verifies Firebase-specific claims
- Public key caching with automatic rotation
- Request size limits prevent large payload attacks
- Comprehensive input validation on all user inputs
Performance
- Automatic public key caching reduces Firebase API calls
- Efficient JWT validation using
jsonwebtokencrate - Minimal memory allocations in hot paths
- Configurable cache duration for optimal performance vs security trade-offs
Logging
The crate uses the log crate for structured logging:
// Initialize logging in your main function
init;
// The middleware will log:
// - INFO: Successful key refreshes
// - WARN: Authentication failures, key fetch issues
// - DEBUG: Cache hits, successful validations
// - ERROR: Configuration issues, repeated failures
Log levels:
DEBUG: Cache operations, successful validationsINFO: Key refresh operationsWARN: Authentication failures, recoverable errorsERROR: Configuration issues, persistent failures
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Development Setup
- Clone the repository
- Run tests:
cargo test - Check formatting:
cargo fmt - Run clippy:
cargo clippy
License
This project is licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT License (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Changelog
0.1.0
- Initial release
- Firebase JWT validation
- Automatic key caching
- Production-ready error handling
- Comprehensive security features