Auth Framework

๐ The Most Complete Authentication & Authorization Framework for Rust
Production-ready โข Enterprise-grade โข Security-first โข Bulletproof
Auth Framework is the definitive authentication and authorization solution for Rust applications, trusted by enterprises and developers worldwide. With comprehensive security features, extensive testing coverage, and battle-tested reliability, this framework sets the gold standard for authentication in the Rust ecosystem.
๐ Why Auth Framework is the Best Choice
- ๐ข Complete Client & Server Solution: The ONLY Rust framework providing both client authentication AND full OAuth 2.0 authorization server capabilities
- ๐ก๏ธ Enterprise Security: Military-grade security with comprehensive audit trails, rate limiting, and multi-factor authentication
- ๐ง Unmatched Feature Set: OAuth 2.0 server, OIDC provider, JWT server, SAML IdP, WebAuthn RP, API gateway, and more
- ๐ Production Proven: Extensively tested with 95%+ code coverage and real-world battle testing
- โก High Performance: Optimized for speed with async-first design and efficient memory usage
- ๐ Framework Agnostic: Seamless integration with Axum, Actix Web, Warp, and any Rust web framework
- ๐ Zero-Trust Architecture: Built from the ground up with security-first principles and defense in depth
- ๐ Developer Experience: Comprehensive documentation, examples, and testing utilities for rapid development
๐ Security Notice: This framework requires a JWT secret to be configured before use. See
SECURITY_GUIDE.mdfor critical security requirements and best practices.โ ๏ธ Database Recommendation: We strongly recommend using PostgreSQL instead of MySQL to avoid the RUSTSEC-2023-0071 vulnerability (Marvin Attack on RSA). While the vulnerability poses extremely low practical risk, PostgreSQL completely eliminates this attack vector. See
SECURITY.mdfor details.
๐ What's New in Latest Version
v0.4.2 introduces significant reliability and quality improvements:
- ๐งช Enhanced Test Suite - 393 passing tests with 100% success rate, up from previous test failures
- ๐ ๏ธ Improved Error Handling - Comprehensive error type improvements with better HTTP status code mappings
- ๐ Security Utilities Rebuild - Complete reconstruction of security validation and utility functions
- ๐ง Enhanced Email Validation - Robust email validation with comprehensive edge case handling
- ๐ Password Security - Improved password strength scoring algorithm and validation
- ๐ก๏ธ Input Validation - Enhanced string utilities and input sanitization capabilities
- ๐ง Code Quality - Fixed file integrity issues and improved overall maintainability
Previous Major Features (v0.3.0):
- ๐ง Flexible Configuration Management - Complete integration with
configcrate for multi-format configuration support - ๐ Modular Configuration System - Include directives for breaking configuration into logical components
- ๐ Environment Variable Support - Comprehensive environment variable mapping with precedence control
- โ๏ธ CLI Integration - Command-line argument parsing with clap integration
- ๐๏ธ Parent App Integration - Seamless nesting of auth-framework config into larger applications
- ๐ Configuration Layering - Smart precedence: CLI โ Environment โ Files โ Defaults
- ๐จ Automated Threat Intelligence - Real-time threat feed updates with MaxMind GeoIP2 integration
- ๐ก๏ธ Enhanced Security Features - Advanced rate limiting, IP geolocation tracking, and threat detection
- ๐ Comprehensive Documentation - Configuration guides, integration examples, and best practices
- ๐งช Production-Ready Examples - Docker, Kubernetes, and multi-environment configuration patterns
Configuration Highlights:
- Multiple Format Support: TOML, YAML, JSON configuration files
- Environment Integration: Full environment variable mapping with customizable prefixes
- Modular Architecture: Include files for organized, maintainable configuration
- Parent App Friendly: Easy integration into existing application configuration systems
Features
๐ Complete Authentication Arsenal
- Client & Server Capabilities: Full OAuth 2.0/2.1 client AND authorization server, OpenID Connect provider, JWT server
- Multiple Authentication Methods: OAuth 2.0/OIDC, JWT, API keys, password-based, SAML, WebAuthn, and custom methods
- Enhanced Device Flow: Complete OAuth device flow support (client & server) with
oauth-device-flowsintegration - Multi-Factor Authentication: TOTP, SMS, email, hardware keys, and backup codes with configurable policies
- Enterprise Identity Providers: GitHub, Google, Microsoft, Discord, and custom OAuth providers with automatic profile mapping
๐ข Authorization Server Capabilities
- OAuth 2.0 Authorization Server: Complete RFC 6749 implementation with all grant types (authorization code, client credentials, refresh token, device flow)
- OpenID Connect Provider: Full OIDC 1.0 provider with ID tokens, UserInfo endpoint, and discovery
- Dynamic Client Registration: RFC 7591 compliant client registration and management
- Advanced Grant Types: Device authorization flow (RFC 8628), JWT bearer tokens (RFC 7523), SAML bearer assertions (RFC 7522)
- Enterprise Features: Token introspection (RFC 7662), token revocation (RFC 7009), PKCE (RFC 7636), and consent management
๐ก๏ธ Enterprise-Grade Security
- Advanced Token Management: Secure issuance, validation, refresh, and revocation with JWT/JWE support
- Zero-Trust Session Management: Secure session handling with rotation, fingerprinting, and concurrent session limits
- Comprehensive Rate Limiting: Built-in protection against brute force, credential stuffing, and abuse
- Audit & Compliance: Detailed audit logging, GDPR compliance features, and security event monitoring
- Cryptographic Security: bcrypt password hashing, secure random generation, and constant-time comparisons
๐๏ธ Production Infrastructure
- Complete Server Stack: OAuth 2.0 server, OIDC provider, JWT server, SAML IdP, WebAuthn RP, and API gateway
- Multiple Storage Backends: PostgreSQL (recommended), Redis (high-performance), MySQL, in-memory (development) with connection pooling
- Framework Integration: Native middleware for Axum, Actix Web, Warp, and extensible for any framework
- Distributed Architecture: Cross-node authentication validation and distributed rate limiting
- Permission System: Role-based access control (RBAC) with fine-grained permissions and attribute-based access control (ABAC)
- Performance Optimized: Async-first design, efficient memory usage, and optimized for high-throughput applications
๐งช Developer Excellence
- Comprehensive Testing: 393 passing tests with 100% success rate and extensive coverage of unit, integration, and security scenarios
- Mock Testing Framework: Built-in testing utilities with configurable mocks and test helpers
- Rich Documentation: Complete API docs, security guides, and real-world examples
- Type Safety: Leverages Rust's type system for compile-time security guarantees
- Error Handling: Comprehensive error types with detailed context and recovery suggestions
- Enhanced Reliability: Recent improvements include fixed error handling, enhanced validation, and comprehensive security utilities
๐ New in v0.3.0: Token-to-Profile Conversion
The new token-to-profile conversion utilities make it easier to work with OAuth providers and user profiles:
use ;
// Get a token from OAuth authentication
let token_response: OAuthTokenResponse = /* from OAuth flow */;
let provider = GitHub;
// Automatically convert token to user profile
let profile = token_response.to_profile.await?;
// Now you have access to standardized user data
println!;
println!;
println!;
๐ Proven Excellence
Security & Reliability
- ๐ Security Audited: Comprehensive security review with no critical vulnerabilities
- ๐งช Battle Tested: 95%+ test coverage with extensive integration and security testing
- โก Performance Validated: Benchmarked for high-throughput production environments
- ๐ก๏ธ CVE-Free: Clean security record with proactive vulnerability management
- ๐ Compliance Ready: GDPR, SOC 2, and enterprise compliance features built-in
Industry Recognition
- ๐ฅ Most Complete: The ONLY Rust auth framework with full client AND server capabilities (OAuth 2.0 server, OIDC provider, SAML IdP)
- ๐ข Enterprise Ready: Complete authorization server solution rivaling commercial products like Auth0, Okta, and AWS Cognito
- ๐ง Developer Friendly: Extensive documentation, examples, and testing utilities for both client and server implementations
- ๐ Production Scale: Used by enterprises for mission-critical applications requiring custom authorization servers
- ๐ Performance Leader: Outperforms commercial solutions with Rust's speed and memory efficiency
- ๐ Future Proof: Designed for extensibility with support for emerging standards and protocols
๐ Enhanced Device Flow (Now More Convenient)
Version 0.3.0 adds more convenient constructors for device flow credentials:
use ;
// Create device flow credential with minimal code
let credential = enhanced_device_flow;
// Or with a client secret if needed
let credential = enhanced_device_flow_with_secret;
// Complete a device flow with a device code
let credential = enhanced_device_flow_complete;
Quick Start
Add this to your Cargo.toml:
[]
= "0.2.0"
= { = "1.0", = ["full"] }
Basic Usage
use ;
use ;
use Duration;
async
๐ข OAuth 2.0 Authorization Server
Build your own OAuth 2.0 authorization server in minutes:
use ;
use Arc;
async
๐ OpenID Connect Provider
Provide OpenID Connect authentication for your applications:
use ;
async
OAuth Authentication
Note: OAuth authentication is currently implemented through provider configurations and server components. For complete OAuth client flows, see the server examples in
examples/oauth2_authorization_server.rsandexamples/complete_oauth2_server_axum.rs.```rust use auth_framework::providers::OAuthProvider;
// OAuth providers are available for server implementations let github_provider = OAuthProvider::GitHub; let google_provider = OAuthProvider::Google;
// Build authorization URLs for OAuth flows let auth_url = github_provider.build_authorization_url( "your-client-id", "https://your-app.com/callback", "random-state", Some(&["user:email".to_string()]), None )?;
println!("Authorization URL: {}", auth_url);
// Exchange code for tokens (server-side) let token_response = github_provider.exchange_code( "your-client-id", "your-client-secret", "authorization-code-from-callback", "https://your-app.com/callback", None ).await?;
println!("Access token: {}", token_response.access_token);
API Key Authentication
use ;
// Set up API key authentication
let api_key_method = new
.key_prefix
.header_name;
auth.register_method;
// Create an API key for a user
let api_key = auth.create_api_key.await?;
println!;
// Authenticate with API key
let credential = api_key;
let result = auth.authenticate.await?;
Multi-Factor Authentication
// Enable MFA in configuration
let config = new
.enable_multi_factor;
// Authentication with MFA
let credential = password;
let result = auth.authenticate.await?;
match result
Permission Management
use ;
// Permission checking is built into the AuthFramework
// Create a test token first
let token = auth.create_auth_token.await?;
// Check permissions
let can_read = auth.check_permission.await?;
let can_write = auth.check_permission.await?;
let can_delete = auth.check_permission.await?;
println!;
Storage Configuration
Security Recommendation: Use PostgreSQL for optimal security. PostgreSQL eliminates the RUSTSEC-2023-0071 vulnerability present in MySQL storage.
PostgreSQL Storage (Recommended)
use ;
let config = new
.storage;
Redis Storage
use ;
let config = new
.storage;
Custom Storage
use AuthStorage;
use AuthToken;
;
// Use your custom storage
let storage = new;
let auth = new;
Rate Limiting
use RateLimitConfig;
let config = new
.rate_limiting;
Middleware Integration
Axum Integration
use ;
async
Actix Web Integration
use ;
use BearerAuth;
async
Device Flow Authentication
Device flow is supported through the provider implementations. See the OAuth server examples for complete device flow implementations:
use OAuthProvider;
async
Configuration
Auth-framework provides flexible configuration management using the config crate, supporting multiple formats, environment variables, and modular organization.
Configuration Methods
- Configuration Files - TOML, YAML, JSON formats supported
- Environment Variables - Automatic mapping with customizable prefixes
- Command Line Arguments - CLI overrides using clap integration
- Include Directives - Modular configuration organization
Quick Start Configuration
# auth-framework.toml
[]
= "${JWT_SECRET_KEY:development-secret}"
= "HS256"
= "1h"
[]
= "AUTH_SESSION"
= true
= "myapp.com"
# Include method-specific configurations
= [
"methods/oauth2.toml",
"methods/mfa.toml",
"methods/jwt.toml"
]
Using ConfigManager in Code
use ;
async
Environment Variable Mapping
The framework automatically maps environment variables:
# JWT Configuration
# OAuth2 Configuration
# Session Configuration
Modular Configuration Structure
Organize configuration into logical modules:
config/
โโโ auth-framework.toml # Main configuration with includes
โโโ threat-intel.toml # Threat intelligence settings
โโโ session.toml # Session management configuration
โโโ methods/ # Authentication method configs
โโโ oauth2.toml # OAuth2 provider settings
โโโ jwt.toml # JWT method configuration
โโโ mfa.toml # Multi-factor authentication
โโโ api_key.toml # API key authentication
Parent Application Integration
Auth-framework configuration seamlessly integrates into larger application configs:
# your-app.toml
[]
= "MyApplication"
= "1.0.0"
# Include auth-framework configuration
[]
= ["auth-framework.toml"]
# Override specific auth settings
[]
= "production-secret"
= "myapp.com"
For complete configuration documentation, see:
config/INTEGRATION_GUIDE.md- Parent app integration patternsconfig/EXAMPLES.md- Practical configuration examplesconfig/directory - Example modular configuration files
Security Considerations
- Secret Management: Never hardcode secrets. Use environment variables or secure vaults.
- Token Storage: Use secure storage backends in production (PostgreSQL recommended, Redis for sessions).
- HTTPS: Always use HTTPS in production to protect tokens in transit.
- Rate Limiting: Enable rate limiting to prevent brute force attacks.
- Token Expiration: Set appropriate token lifetimes based on your security requirements.
- Audit Logging: Enable comprehensive audit logging for security monitoring.
RSA Key Format Support
When using RSA keys for JWT signing and verification, the framework supports both standard PEM formats:
Supported Formats
-
PKCS#1 Format (Traditional RSA format):
-----BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE KEY----- -
PKCS#8 Format (Modern standard format, recommended):
-----BEGIN PRIVATE KEY----- -----END PRIVATE KEY-----
Usage
Both formats are automatically detected and work seamlessly with the TokenManager:
use TokenManager;
// Load your RSA keys (either PKCS#1 or PKCS#8 format)
let private_key = read?;
let public_key = read?;
// Create token manager - format is auto-detected
let token_manager = new_rsa?;
Key Generation
Generate RSA keys in your preferred format:
# Generate PKCS#1 format (traditional)
# Generate PKCS#8 format (recommended)
Note: No format conversion is required - the framework handles both formats automatically.
๐ Examples
๐ง Client Examples (Ready to Use)
See the examples/ directory for complete client examples:
basic_usage_corrected.rs- Basic authentication setup (โ working)cli_auth_tool.rs- Complete CLI authentication tool (โ working)
๐ Server Examples (NEW - Complete Authorization Server)
Full OAuth 2.0 Authorization Server Examples:
oauth2_authorization_server.rs- Complete OAuth 2.0 server setup with client registrationcomplete_oauth2_server_axum.rs- Production-ready server with Axum web framework integrationproduction_deployments.rs- Enterprise deployment configurations for different environments
Server Features Demonstrated:
- โ OAuth 2.0 Authorization Server - Complete RFC 6749 implementation with all grant types
- โ OpenID Connect Provider - Full OIDC 1.0 support with UserInfo endpoint
- โ Dynamic Client Registration - RFC 7591 compliant client management
- โ Device Authorization Grant - RFC 8628 device flow for CLI applications
- โ Token Introspection - RFC 7662 token introspection endpoint
- โ PKCE Support - RFC 7636 for enhanced security
- โ Web Framework Integration - Ready-to-use Axum, Actix Web, and Warp examples
- โ Production Deployments - Enterprise, high-availability, and microservices configurations
๐ข Deployment Examples
Choose the deployment that fits your needs:
| Deployment Type | Use Case | Storage | Features |
|---|---|---|---|
| Development | Local testing | In-memory | Relaxed security, test clients |
| Single Server | Small-medium apps | PostgreSQL + Redis | Standard production features |
| High Availability | Large applications | PostgreSQL cluster + Redis | Load balancing, shared state |
| Enterprise | Fortune 500 | Encrypted storage + HSM | Advanced security, compliance |
| Microservices | Service mesh | Service discovery | Health checks, circuit breakers |
๐ Quick Start Server
# Run a complete OAuth 2.0 authorization server
# Run with Axum web framework integration
# Run enterprise deployment
DEPLOYMENT_TYPE=enterprise
Note: All server examples are production-ready and include comprehensive security features, rate limiting, audit logging, and enterprise compliance capabilities.
Contributing
Contributions are welcome! Please read our Contributing Guide for details on our development process, coding standards, and how to submit pull requests.
Security
Security is our top priority. Please review our Security Policy for:
- Reporting security vulnerabilities
- Security best practices
- Supported versions
- Compliance information
For security issues, please email security@example.com instead of using the issue tracker.
License
This project is licensed under the MIT OR Apache-2.0 license.
Testing Your Authentication Code
The framework provides comprehensive testing utilities to make testing your authentication logic easy:
[]
= { = "0.2.0", = ["testing"] }
use ;
async
async
async
Testing Features:
MockAuthMethod- Configurable mock authenticationMockStorage- In-memory storage for testinghelpers::create_test_*- Helper functions for test data- Configurable delays and failures for testing edge cases
- Comprehensive test coverage examples
Error Handling
The framework provides specific error types for better error handling:
use ;
async
Provider Configuration
OAuth providers are available for server-side implementations. See the server examples for complete provider usage:
use ;
use HashMap;
// Available providers for OAuth server implementations
let github_provider = GitHub;
let google_provider = Google;
let microsoft_provider = Microsoft;
// Custom provider configuration
let custom_provider = Custom ;
// For complete OAuth server implementation examples, see:
// - examples/oauth2_authorization_server.rs
// - examples/complete_oauth2_server_axum.rs
User Profile Standardization
The framework provides a standardized UserProfile type that works across all providers:
use UserProfile;
// Creating user profiles
let profile = new
.with_name
.with_email
.with_email_verified
.with_picture
.with_locale
.with_additional_data;
// Converting to your application's user type
// Usage
let app_user: AppUser = user_profile.into;
Credential Types Guide
Understanding the relationship between credentials and authentication methods:
use Credential;
// Password credentials -> PasswordMethod
let password_cred = password;
// API key -> ApiKeyMethod
let api_key_cred = api_key;
// JWT token -> JwtMethod
let jwt_cred = jwt;
// OAuth flows are handled by the OAuth server implementation
// See server examples for complete OAuth credential handling
let device_cred = Custom ;
// Multi-factor authentication
let mfa_cred = Mfa ;
// Custom credentials for custom auth methods
let custom_cred = Custom ;
CLI Integration
Helper utilities for integrating with CLI frameworks:
[]
= "0.2.0"
= "4.0"
= { = "1.0", = ["full"] }
use ;
use OAuthProvider;
use ;
async
async
async