Auth Framework

๐ The Most Complete Authentication & Authorization Framework for Rust
Production-ready โข Enterprise-grade โข Security-first โข Bulletproof
โก Quick Start - Get Running in Seconds
No Rust installation required! Use our precompiled binaries:
# Linux/macOS - One-line installation
|
# Windows PowerShell - One command
|
# Docker - Instant deployment
That's it! Server running at http://localhost:8080 ๐
๐ Full Deployment Guide โข ๐ณ Docker Deployment โข ๐ ๏ธ Configuration Guide
Note: While the crates.io published version of this crate is fully functional and well documented on docs.rs, this repo's code may or may not be at the current time. We are in the middle of a lot of changes. Please wait for the dust to settle. We've just split the Python and JavaScript SDKs into separate repositories which broke a few things because they were tightly coupled and, although the Python SDK is more or less fixed, the JavaScript SDK still needs work (no one was using it so it is on the proverbial back burner because we need to get the parts companies use fixed first). We've just added support for 3rd party storage backends and haven't finished updating documentation for that. We are currently in the process of splitting the project from a monolithic Rust library into a separate server and client design and, while the library still works and the server is functional and all tests pass, the design is still in a state of flux and may not currently match the documentation. We are also in the process of changing how official releases from this project are made. When this project was built, it was primarily for use by myself, three companies, and a few friends' projects. It was built to high standards and worked flawlessly. However, as time went on, it became obvious that we needed to be able to support multiple versions of this project as a couple of the companies using it are more cautious than we expected about upgrading to new releases with breaking changes and still need fixes put in place for older versions until they are ready to make the jump. As such, when the next release happens, we will be splitting this repo into branches for each major version and continuing to provide bug fixes for older versions as we find them. We also decided we need to provide precompiled server releases. While there is nothing wrong with building the Rust code yourself, developers coding in other languages (using our Python and Javascript SDKs) should not need to build the Rust-based servers before being able to use this project in their language of choice. As such, we will be providing precompiled binaries starting with the next release.
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.5.0-rc1 - OAuth 2.1 Complete Implementation & Enhanced Security:
- ๐ OAuth 2.1 Full Compliance - Complete OAuth 2.1 authorization server implementation
- Token Introspection (RFC 7662) - 9 comprehensive tests
- Pushed Authorization Requests / PAR (RFC 9126) - 9 comprehensive tests
- Device Authorization Flow (RFC 8628) - 14 comprehensive tests
- End-to-end OAuth 2.1 flows - 9 integration tests
- 41 OAuth tests total, 100% passing
- ๐ก๏ธ Advanced Security Features - Production-grade security enhancements
- Rate Limiting - 12 tests covering burst protection and distributed systems
- DoS Protection - 10 tests including Slowloris defense and resource exhaustion
- IP Blacklisting - 12 tests for threat prevention and geolocation blocking
- MFA Flows - 18 tests covering TOTP, enrollment, and recovery
- 52 security tests total, 100% passing
- ๐ Test Suite Excellence - 93 comprehensive tests (100% passing)
- 41 OAuth 2.1 protocol tests
- 52 security implementation tests
- Full integration test coverage
- Performance validation complete
- ๐๏ธ Production Ready - Complete authorization server capabilities
- Token introspection for resource servers
- PAR for enhanced security workflows
- Device flow for IoT and CLI applications
- Multi-factor authentication enforcement
- DoS and DDoS protection built-in
Previous Release (v0.5.0-alpha) - Phase 2: Password & Email Validation Complete:
- ๐ Enhanced Password Validation - Completely overhauled password validation system with granular complexity requirements
- Added 8 new SecurityConfig fields for fine-grained password policy control
- Advanced minimum complexity criteria system (meet N of 4 possible criteria)
- Individual requirement toggles for maximum flexibility
- Maintains full backward compatibility
- ๏ฟฝ RFC 5322 Email Validation - Industry-standard email validation using
email_addresscrate- Full RFC 5322 compliance for professional-grade email format validation
- Advanced parsing with configurable options
- Comprehensive edge case handling for production use
- โ๏ธ Configuration System Overhaul - Enhanced SecurityConfig with comprehensive security controls
- Added
LockoutConfigstructure for account lockout management - Added
OAuth2SecurityConfigfor OAuth2-specific security settings - Enhanced helper methods with all new security fields
- Added
- ๐งช Enhanced Test Suite - 405 passing tests with comprehensive validation coverage
- 12 new validation tests covering all enhancement scenarios
- Password complexity criteria testing with various combinations
- Email validation testing with valid/invalid cases and edge cases
Previous Release (v0.4.2):
- 393 passing tests with 100% success rate, comprehensive error handling improvements
- Security utilities rebuild, enhanced email validation, improved password security
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: 93 passing tests with 100% success rate and extensive coverage of OAuth 2.1, security, and integration 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: OAuth 2.1 compliance, advanced security features, and comprehensive validation
๐ 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