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.

§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::{AuthFramework, AuthConfig, methods::JwtMethod};
use std::time::Duration;

    // Configure the auth framework
    let config = AuthConfig::new()
        .token_lifetime(Duration::from_secs(3600))
        .refresh_token_lifetime(Duration::from_secs(86400 * 7));

    // Create the auth framework
    let mut auth = AuthFramework::new(config);

    // Register a JWT authentication method
    let jwt_method = JwtMethod::new()
        .secret_key("your-secret-key")
        .issuer("your-service");

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

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

    // Create a token
    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");
        }
    }

§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 crate::auth::AuthFramework;
pub use crate::auth::AuthResult;
pub use crate::auth::AuthStats;
pub use crate::auth::UserInfo;
pub use authentication::credentials::Credential;
pub use config::AuthConfig;
pub use config::app_config::AppConfig;
pub use config::app_config::ConfigBuilder;
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::UserProfile;
pub use tokens::AuthToken;
pub use ws_security::UsernameToken;
pub use ws_security::WsSecurityClient;
pub use ws_security::WsSecurityConfig;
pub use ws_security::WsSecurityHeader;
pub use ws_trust::RequestSecurityToken;
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 server::oidc::oidc_backchannel_logout::BackChannelLogoutConfig;
pub use server::oidc::oidc_backchannel_logout::BackChannelLogoutManager;
pub use server::oidc::oidc_backchannel_logout::BackChannelLogoutRequest;
pub use server::oidc::oidc_backchannel_logout::BackChannelLogoutResponse;
pub use server::oidc::oidc_backchannel_logout::LogoutEvents;
pub use server::oidc::oidc_backchannel_logout::LogoutTokenClaims;
pub use server::oidc::oidc_backchannel_logout::NotificationResult;
pub use server::oidc::oidc_backchannel_logout::RpBackChannelConfig;
pub use server::oidc::oidc_frontchannel_logout::FailedNotification;
pub use server::oidc::oidc_frontchannel_logout::FrontChannelLogoutConfig;
pub use server::oidc::oidc_frontchannel_logout::FrontChannelLogoutManager;
pub use server::oidc::oidc_frontchannel_logout::FrontChannelLogoutRequest;
pub use server::oidc::oidc_frontchannel_logout::FrontChannelLogoutResponse;
pub use server::oidc::oidc_frontchannel_logout::RpFrontChannelConfig;
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 server::ClientRegistrationRequest;
pub use server::ClientType;
pub use server::WorkingServerConfig;
pub use server::core::client_registration::ClientRegistrationRequest as ServerClientRegistrationRequest;
pub use server::core::client_registry::ClientType as ServerClientType;
pub use server::DpopManager;
pub use server::MetadataProvider;
pub use server::OAuth2Server as ServerOAuth2Server;
pub use server::PARManager;
pub use server::PrivateKeyJwtManager;
pub use server::TokenIntrospectionService;
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::AccessCondition;
pub use authorization::AuthorizationEngine;
pub use authorization::Permission as AuthzPermission;
pub use authorization::Role as AuthzRole;
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_session::SessionState as SecureSessionState;
pub use security::secure_utils::SecureComparison;
pub use security::secure_utils::SecureRandomGen;
pub use session::manager::DeviceInfo;
pub use session::manager::Session;
pub use session::manager::SessionConfig;
pub use session::manager::SessionManager as LegacySessionManager;
pub use session::manager::SessionState;
pub use utils::rate_limit::RateLimiter;
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 and monitoring for RBAC systems
api
REST API Server Module
audit
Comprehensive audit logging and security event tracking.
auth
Main authentication framework implementation.
auth_modular
Modular authentication framework with component-based architecture.
authentication
Authentication modules
authorization
Role-Based Access Control (RBAC) and Authorization framework.
authorization_enhanced
Enhanced Authorization Module with role-system v1.0 integration
builders
Builder patterns and ergonomic helpers for the Auth Framework
cli
config
Configuration types for the authentication framework.
deployment
distributed_rate_limiting
Distributed Rate Limiting System
errors
Comprehensive error types for the AuthFramework.
integrations
methods
Authentication method implementations.
migration
Migration utilities for transitioning to role-system v1.0
migrations
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 and Metrics Collection Module
oauth2_enhanced_storage
Enhanced OAuth2 token and code storage with proper validation
oauth2_server
OAuth 2.0 Authorization Server Implementation
permissions
prelude
Auth Framework Prelude
profile_utils
Utilities for token-to-profile conversion and user profile management.
providers
OAuth provider configurations and implementations.
saml_assertions
SAML 2.0 Assertion Support for WS-Security
sdks
SDK Generation Module
security
server
Server-side authentication and authorization implementations.
session
Session management modules
storage
testing
Testing utilities and infrastructure
threat_intelligence
Automated Threat Intelligence Feed Management
tokens
Token management and validation for the authentication framework.
user_context
User context and authentication state management
utils
Utility functions for the authentication framework.
ws_security
WS-Security 1.1 Client Implementation
ws_trust
WS-Trust 1.3 Security Token Service (STS) Support

Macros§

test_with_containers
test_with_env
Macros for simplified test environment setup