MCPcopy Index your code
hub / github.com/ciresnave/auth-framework

github.com/ciresnave/auth-framework @v0.4.2

Chat with this repo
repository ↗ · DeepWiki ↗ · release v0.4.2 ↗ · + Follow
4,779 symbols 11,615 edges 248 files 2,389 documented · 50%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Auth Framework

Auth Framework

🏆 The Most Complete Authentication & Authorization Framework for Rust

Production-ready • Enterprise-grade • Security-first • Bulletproof

Crates.io Documentation License Security Audit


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.md for 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.md for 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 config crate 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-flows integration
  • 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 auth_framework::{TokenToProfile, OAuthProvider, OAuthTokenResponse};

// Get a token from OAuth authentication
let token_response: OAuthTokenResponse = /* from OAuth flow */;
let provider = OAuthProvider::GitHub;

// Automatically convert token to user profile
let profile = token_response.to_profile(&provider).await?;

// Now you have access to standardized user data
println!("User ID: {}", profile.id.unwrap_or_default());
println!("Username: {}", profile.username.unwrap_or_default());
println!("Email: {}", profile.email.unwrap_or_default());

🏅 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 auth_framework::{Credential, OAuthProvider};

// Create device flow credential with minimal code
let credential = Credential::enhanced_device_flow(
    OAuthProvider::GitHub,
    "client_id",
    vec!["user", "repo"]
);

// Or with a client secret if needed
let credential = Credential::enhanced_device_flow_with_secret(
    OAuthProvider::Google,
    "client_id",
    "client_secret",
    vec!["email", "profile"]
);

// Complete a device flow with a device code
let credential = Credential::enhanced_device_flow_complete(
    OAuthProvider::Microsoft,
    "client_id",
    "device_code",
    vec!["user.read"]
);

Quick Start

Add this to your Cargo.toml:

[dependencies]
auth-framework = "0.2.0"
tokio = { version = "1.0", features = ["full"] }

Basic Usage

use auth_framework::{AuthFramework, AuthConfig};
use auth_framework::methods::{JwtMethod, AuthMethodEnum};
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Set environment for development/testing (allows memory storage)
    std::env::set_var("ENVIRONMENT", "development");

    // Configure the auth framework with required JWT secret
    let jwt_secret = std::env::var("JWT_SECRET")
        .unwrap_or_else(|_| "your-secure-jwt-secret-at-least-32-characters-long".to_string());

    let config = AuthConfig::new()
        .token_lifetime(Duration::from_secs(3600))
        .refresh_token_lifetime(Duration::from_secs(86400 * 7))
        .secret(jwt_secret);

    // Create the auth framework (storage is handled internally)
    let mut auth = AuthFramework::new(config);

    // Register a JWT authentication method
    let jwt_method = JwtMethod::new()
        .secret_key("your-secure-jwt-secret-at-least-32-characters-long")
        .issuer("your-service");

    auth.register_method("jwt", AuthMethodEnum::Jwt(jwt_method));

    // Initialize the framework
    auth.initialize().await?;

    // Create a JWT token for testing
    let token = auth.create_auth_token(
        "user123",
        vec!["read".to_string(), "write".to_string()],
        "jwt",
        None,
    ).await?;

    // Validate the token
    if auth.validate_token(&token).await? {
        println!("Token is valid!");

        // Check permissions
        if auth.check_permission(&token, "read", "documents").await? {
            println!("User has permission to read documents");
        }
    }

    Ok(())
}

🏢 OAuth 2.0 Authorization Server

Build your own OAuth 2.0 authorization server in minutes:

```rust use auth_framework::{ AuthServer, AuthServerConfig, OAuth2ServerConfig, OidcProviderConfig, ClientRegistrationRequest, ClientType, storage::MemoryStorage, }; use std::sync::Arc;

[tokio::main]

async fn main() -> Result<(), Box> { // Configure the authorization server let oauth2_config = OAuth2ServerConfig { issuer: "https://auth.yourcompany.com".to_string(), authorization_endpoint: "/oauth2/authorize".to_string(), token_endpoint: "/oauth2/token".to_string(), require_pkce_for_public_clients: true, require_consent: true, ..Default::default() };

let server_config = AuthServerConfig {
    oauth2_config,
    oidc_config: OidcProviderConfig::default(),
    ..Default::default()
};

// Create storage backend
let storage = Arc::new(MemoryStorage::new());

// Create the authorization server
let auth_server = AuthServer::new(server_config, storage).await?;
auth_server.initialize().await?;

// Register a client application
let client_request = ClientRegistrationRequest {
    client_name: "My Web App".to_string(),
    redirect_uris: vec!["https://myapp.com/callback".to_string()],
    grant_types: vec!["authorization_code".to_string(), "refresh_token".to_string()],
    response_typ

Extension points exported contracts — how you extend this code

AuthMethod (Interface)
Trait for authentication methods. [6 implementers]
src/methods/mod.rs
AuthStorage (Interface)
(no doc) [10 implementers]
src/storage/core.rs
AuthRouterExt (Interface)
Ergonomic middleware methods for Router [1 implementers]
src/integrations/axum.rs
ConfigWatcher (Interface)
Trait for configuration change watchers [1 implementers]
src/deployment/config.rs
ExtractProfile (Interface)
Trait for automatic extraction of user profiles from responses [1 implementers]
src/profile_utils/mod.rs
DelegationManager (Interface)
Traits for storage and management
src/authentication/advanced_auth.rs
ServerConfig (Interface)
Base configuration trait that all server configs can implement
src/server/core/common_config.rs
DatabaseValue (Interface)
Database value trait for query parameters
src/authorization_enhanced/storage.rs

Core symbols most depended-on inside this repo

clone
called by 902
src/tokens/mod.rs
is_empty
called by 308
src/security/secure_utils.rs
len
called by 306
src/security/secure_utils.rs
as_str
called by 285
src/security/secure_mfa.rs
get
called by 218
src/config/config_manager.rs
get
called by 203
src/server/core/common_http.rs
collect
called by 179
src/monitoring/collectors.rs
as_bytes
called by 129
src/security/secure_utils.rs

Shape

Method 2,432
Function 1,168
Class 908
Enum 211
Interface 60

Languages

Rust93%
Python4%
TypeScript2%

Modules by API surface

src/auth.rs98 symbols
src/server/oidc/oidc_extensions.rs72 symbols
src/builders.rs69 symbols
src/deployment/monitoring.rs59 symbols
src/server/core/federated_authentication_orchestration.rs58 symbols
src/server/token_exchange/advanced_token_exchange.rs57 symbols
src/permissions.rs57 symbols
src/tokens/mod.rs55 symbols
tests/comprehensive_api_tests.rs52 symbols
src/storage/core.rs51 symbols
src/providers.rs51 symbols
src/server/oauth/rich_authorization_requests.rs50 symbols

Datastores touched

auth_frameworkDatabase · 1 repos
auth_dbDatabase · 1 repos
authframeworkDatabase · 1 repos
auth_testDatabase · 1 repos
authdbDatabase · 1 repos
test_dbDatabase · 1 repos

For agents

$ claude mcp add auth-framework \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact