Skip to main content

Crate auth_framework

Crate auth_framework 

Source
Expand description

§Auth Framework

A comprehensive authentication and authorization framework for Rust applications.

This crate provides a unified interface for various authentication methods, token management, permission checking, and secure credential handling with a focus on distributed systems.

§API Orientation

§Features

  • Multiple authentication methods (OAuth, API keys, JWT, etc.)
  • Token issuance, validation, and refresh with RSA and HMAC signing
  • RSA key format support: PKCS#1 and PKCS#8 formats auto-detected
  • Role-based access control integration
  • Permission checking and enforcement
  • Secure credential storage
  • Authentication middleware for web frameworks
  • Distributed authentication with cross-node validation
  • Single sign-on capabilities
  • Multi-factor authentication support
  • Audit logging of authentication events
  • Rate limiting and brute force protection
  • Session management
  • Password hashing and validation
  • Customizable authentication flows

§Quick Start

use auth_framework::prelude::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Build configuration.  JWT secret must be at least 32 characters.
    let config = AuthConfig::new()
        .token_lifetime(std::time::Duration::from_secs(3600))
        .secret(std::env::var("JWT_SECRET")
            .unwrap_or_else(|_| "replace-with-a-32-char-random-secret!!".to_string()));

    let mut auth = AuthFramework::new(config);
    auth.initialize().await?;

    // Register a user.
    let user_id = auth.users().register("alice", "alice@example.com", "s3cr3t!").await?;

    // Issue a token via the grouped token accessor.
    let token = auth.tokens().create(&user_id, &["read"], "jwt", None).await?;

    // Validate and authorize.
    if auth.tokens().validate(&token).await? {
        if auth.authorization().check(&token, "read", "documents").await? {
            println!("Alice may read documents.");
        }
    }

    Ok(())
}

See prelude for the full set of re-exported types, and the accessor groups AuthFramework::users, AuthFramework::sessions, AuthFramework::tokens, AuthFramework::authorization, AuthFramework::mfa, AuthFramework::monitoring, AuthFramework::audit, and AuthFramework::admin for organized entry points into each capability area.

§Security Considerations

  • Always use HTTPS in production
  • Use strong, unique secrets for token signing
  • Enable rate limiting to prevent brute force attacks
  • Regularly rotate secrets and keys
  • Monitor authentication events for suspicious activity
  • Follow the principle of least privilege for permissions

See the Security Policy for comprehensive security guidelines.

Re-exports§

pub use server::oauth::oauth2_enhanced_storage;
pub use server::oauth::oauth2_server;
pub use crate::auth::AdminOperations;
pub use crate::auth::AuditOperations;
pub use crate::auth::AuthFramework;
pub use crate::auth::AuthResult;
pub use crate::auth::AuthStats;
pub use crate::auth::AuthorizationOperations;
pub use crate::auth::MaintenanceOperations;
pub use crate::auth::MfaOperations;
pub use crate::auth::MonitoringOperations;
pub use crate::auth::SessionOperations;
pub use crate::auth::TokenOperations;
pub use crate::auth::UserInfo;
pub use crate::auth::UserOperations;
pub use crate::auth_modular::AuthFramework as ModularAuthFramework;
pub use crate::maintenance::BackupReport;
pub use crate::maintenance::MaintenanceSnapshot;
pub use crate::maintenance::MigrationFileReport;
pub use crate::maintenance::ResetReport;
pub use crate::maintenance::RestoreReport;
pub use crate::maintenance::SnapshotManifest;
pub use authentication::credentials::Credential;
pub use config::app_config::ConfigBuilder as AppConfigBuilder;
pub use config::config_manager::AuthFrameworkSettings;
pub use config::config_manager::ConfigBuilder as LayeredConfigBuilder;
pub use config::config_manager::ConfigManager;
pub use config::AuthConfig;
pub use config::AuthConfigBuilder;
pub use config::CorsConfig;
pub use config::app_config::AppConfig;
pub use errors::AuthError;
pub use errors::Result;
pub use methods::ApiKeyMethod;
pub use methods::AuthMethod;
pub use methods::JwtMethod;
pub use methods::MethodResult;
pub use methods::OAuth2Method;
pub use methods::PasswordMethod;
pub use api::ApiError;
pub use api::ApiResponse;
pub use api::ApiServer;
pub use api::ApiState;
pub use providers::generate_pkce;
pub use permissions::Permission;
pub use permissions::PermissionChecker;
pub use permissions::Role;
pub use profile_utils::ExtractProfile;
pub use profile_utils::TokenToProfile;
pub use providers::DeviceAuthorizationResponse;
pub use providers::OAuthProvider;
pub use providers::OAuthProviderConfig;
pub use providers::ProviderProfile;
pub use tokens::AuthToken;
pub use server::oidc::Address;
pub use server::oidc::AuthorizationValidationResult;
pub use server::oidc::IdTokenClaims;
pub use server::oidc::Jwk;
pub use server::oidc::JwkSet;
pub use server::oidc::LogoutResponse;
pub use server::oidc::OidcAuthorizationRequest;
pub use server::oidc::OidcConfig;
pub use server::oidc::OidcDiscoveryDocument;
pub use server::oidc::OidcProvider;
pub use server::oidc::SubjectType;
pub use server::oidc::UserInfo as OidcUserInfo;
pub use oauth2_server::AuthorizationRequest;
pub use oauth2_server::GrantType;
pub use oauth2_server::OAuth2Config;
pub use oauth2_server::OAuth2Server;
pub use oauth2_server::ResponseType;
pub use oauth2_server::TokenRequest;
pub use oauth2_server::TokenResponse;
pub use client::ClientConfig;
pub use client::ClientConfigBuilder;
pub use client::ClientType;
pub use server::ClientRegistrationRequest;
pub use server::WorkingServerConfig;
pub use audit::AuditEvent;
pub use audit::AuditEventType;
pub use audit::AuditLogger;
pub use audit::EventOutcome;
pub use audit::RiskLevel;
pub use authentication::mfa::MfaManager as LegacyMfaManager;
pub use authentication::mfa::MfaMethodType;
pub use authentication::mfa::TotpProvider;
pub use authorization::AbacPermission as AuthzPermission;
pub use authorization::AbacRole as AuthzRole;
pub use authorization::AccessCondition;
pub use authorization::AuthorizationEngine;
pub use security::secure_jwt::SecureJwtClaims;
pub use security::secure_jwt::SecureJwtConfig;
pub use security::secure_jwt::SecureJwtValidator;
pub use security::secure_mfa::SecureMfaService;
pub use security::secure_session::DeviceFingerprint;
pub use security::secure_session::SecureSession;
pub use security::secure_session::SecureSessionConfig;
pub use security::secure_session::SecureSessionManager;
pub use security::secure_session::SecurityFlags;
pub use security::secure_utils::SecureComparison;
pub use security::secure_utils::SecureRandomGen;
pub use session::manager::SessionManager as LegacySessionManager;
pub use session::manager::DeviceInfo;
pub use session::manager::Session;
pub use session::manager::SessionConfig;
pub use session::manager::SessionManager;
pub use session::manager::SessionState;
pub use utils::rate_limit::RateLimiter;
pub use tenant::TenantContext;
pub use tenant::TenantId;
pub use tenant::TenantMetadata;
pub use tenant::TenantRegistry;
pub use tenant::TenantRegistryBuilder;
pub use monitoring::HealthCheckResult;
pub use monitoring::HealthStatus;
pub use monitoring::MetricDataPoint;
pub use monitoring::MetricType;
pub use monitoring::MonitoringConfig;
pub use monitoring::MonitoringManager;
pub use monitoring::PerformanceMetrics;
pub use monitoring::SecurityEvent;
pub use monitoring::SecurityEventSeverity;
pub use monitoring::SecurityEventType;
pub use auth::SessionCoordinationStats;

Modules§

analytics
Analytics collection and reporting. Analytics and monitoring for RBAC systems.
api
REST API Server Module
audit
Audit logging of authentication and authorization events. Comprehensive audit logging and security event tracking.
auth
Primary authentication framework — start here.
auth_modular
Advanced component-oriented framework.
auth_operations
Grouped operation facades over AuthFramework.
authentication
Supporting authentication data types.
authorization
Role-based and attribute-based access control (RBAC/ABAC). Role-Based Access Control (RBAC) and Authorization framework.
authorization_enhanced
Enhanced Authorization Module with role-system v1.0 integration
builders
Ergonomic builders and prelude for better developer experience. Builder patterns and ergonomic helpers for the Auth Framework
cli
Command-line interface utilities.
client
OAuth 2.0 client type definitions (RFC 6749 §2.1). OAuth 2.0 client types — canonical definitions (RFC 6749 §2.1).
config
Configuration types and management.
deployment
Deployment, scaling, and infrastructure management.
distributed
Distributed authentication: cross-node token validation and cluster coordination. Distributed session store abstraction.
errors
Error types and the crate-wide Result alias. Comprehensive error types for the AuthFramework.
integrations
Ready-made middleware and extractors for popular web frameworks.
maintenance
Backup, restore, and reset utilities. Maintenance utilities: snapshots, data export, and health checks.
methods
Authentication method implementations (JWT, OAuth2, API keys, passwords, SAML). Authentication method implementations.
migration
Schema migration utilities for role-system v1.0 integration. Migration utilities for transitioning to role-system v1.0
migrations
SQL migration scripts for database backends. Database migration system for auth-framework. This module provides tools for managing database schema changes and ensuring proper setup of authentication-related tables.
monitoring
Monitoring, health checks, and performance metrics. Monitoring and Metrics Collection Module
permissions
Permission and role definitions for access control. Permission and role-based access control (RBAC / ABAC).
prelude
Convenience re-exports for common types — use auth_framework::prelude::*. Auth Framework Prelude
profile_utils
Helpers for extracting user profiles from tokens and provider responses. Utilities for token-to-profile conversion and user profile management.
protocols
Protocol-level types shared across OAuth, OIDC, and SAML flows.
providers
OAuth 2.0 provider configuration and PKCE helpers. OAuth provider configurations and implementations.
sdks
SDK Generation Module
security
Security utilities: rate limiting, DoS protection, IP blocking, and JWT hardening. Security primitives and hardened implementations.
server
Server-side OAuth 2.0 / OIDC / FAPI protocol implementations. Server-side authentication and authorization implementations.
session
Session lifecycle, device fingerprinting, and risk scoring. Session management modules
storage
Storage backends and the AuthStorage trait.
tenant
Multi-tenant support for native multi-tenant deployments. Multi-tenant support for AuthFramework
testing
Test helpers and mock implementations for downstream testing. Testing utilities and infrastructure
threat_intelligence
Threat intelligence feeds and IP reputation services. Automated Threat Intelligence Feed Management
tokens
Token creation, validation, rotation, and JWKS support. Token management and validation for the authentication framework.
types
Domain-specific newtypes (Roles, Scopes, Permissions, etc.). Common domain types used throughout the AuthFramework.
user_context
User context and session enrichment. User context and authentication state management
utils
Internal utility functions. Utility modules for the AuthFramework.

Macros§

test_with_containers
test_with_env
Macros for simplified test environment setup

Type Aliases§

CoreUserInfoDeprecated
Deprecated alias — use UserInfo directly.
ServerClientRegistrationRequestDeprecated
Deprecated alias for ClientRegistrationRequest.