Expand description
Authentication and authorization mechanisms Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
This file is part of Ri. The Ri project belongs to the Dunimd Team.
Licensed under the Apache License, Version 2.0 (the “License”); You may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
§Authentication Module
This module provides comprehensive authentication and authorization functionality for Ri, offering multiple authentication methods and a robust permission system.
§Key Components
- RiAuthModule: Main auth module implementing service module traits
- RiAuthConfig: Configuration for authentication behavior
- RiJWTManager: JWT token management for stateless authentication
- RiSessionManager: Session management for stateful authentication
- RiPermissionManager: Permission and role management
- RiOAuthManager: OAuth provider integration
- RiJWTClaims: JWT token claims structure
- RiJWTValidationOptions: JWT validation options
- RiOAuthProvider: OAuth provider interface
- RiOAuthToken: OAuth token structure
- RiOAuthUserInfo: OAuth user information
- RiPermission: Permission structure
- RiRole: Role structure with permissions
- RiSession: Session structure
§Design Principles
- Multiple Authentication Methods: Supports JWT, sessions, OAuth, and API keys
- Configurable: Highly configurable authentication behavior
- Async Support: Full async/await compatibility for session and OAuth operations
- Role-Based Access Control: Comprehensive permission system with roles
- Stateless and Stateful Options: Supports both stateless (JWT) and stateful (session) authentication
- Service Module Integration: Implements service module traits for seamless integration
- Thread-safe: Uses Arc and RwLock for safe concurrent access
- Non-critical: Auth failures should not break the entire application
- Extensible: Easy to add new authentication methods and OAuth providers
- Secure by Default: Sensible default configurations for security
§Usage
use ri::prelude::*;
use ri::auth::{RiAuthConfig, RiJWTManager, RiJWTClaims};
use serde_json::json;
async fn example() -> RiResult<()> {
// Create auth configuration
let auth_config = RiAuthConfig {
enabled: true,
jwt_secret: "secure-secret-key".to_string(),
jwt_expiry_secs: 3600,
session_timeout_secs: 86400,
oauth_providers: vec![],
enable_api_keys: true,
enable_session_auth: true,
};
// Create auth module
let auth_module = RiAuthModule::new(auth_config);
// Get JWT manager
let jwt_manager = auth_module.jwt_manager();
// Create JWT claims
let claims = RiJWTClaims {
sub: "user-123".to_string(),
email: "user@example.com".to_string(),
roles: vec!["user".to_string()],
permissions: vec!["read:data".to_string()],
extra: json!({ "custom": "value" }),
};
// Generate JWT token
let token = jwt_manager.generate_token(claims)?;
println!("Generated JWT token: {}", token);
// Validate JWT token
let validated_claims = jwt_manager.validate_token(&token)?;
println!("Validated claims: {:?}", validated_claims);
// Get session manager
let session_manager = auth_module.session_manager();
// Create a session
let session = session_manager.write().await.create_session("user-123").await?;
println!("Created session: {}", session.id);
Ok(())
}Structs§
- RiAuth
Config - Configuration for the authentication module.
- RiAuth
Module - Main authentication module for Ri.
- RiJWT
Claims - Represents the claims payload in a JWT token.
- RiJWT
Manager - Core JWT management structure.
- RiJWT
Revocation List - JWT token revocation list for managing invalidated tokens.
- RiJWT
Validation Options - Configuration options for JWT token validation.
- RiOAuth
Manager - OAuth manager for handling multiple identity providers.
- RiOAuth
Provider - OAuth provider configuration.
- RiOAuth
Token - OAuth token response.
- RiOAuth
User Info - OAuth user information.
- RiPermission
- Permission definition for fine-grained access control.
- RiPermission
Manager - Permission manager for handling permissions, roles, and user assignments.
- RiRevoked
Token Info - Information about a revoked JWT token.
- RiRole
- Role definition for grouping permissions.
- RiSecurity
Manager - Security utilities manager for Ri.
- RiSession
- Session structure for tracking user sessions.
- RiSession
Manager - Session manager for handling user sessions.