# Auth Module **Sichere Authentifizierungs- und Autorisierungskomponenten** für das Custom PHP Framework. ## Überblick Das Auth Module bietet umfassende Sicherheitsfeatures für Benutzerauthentifizierung, Passwort-Management und Session-Verwaltung. Es integriert sich nahtlos mit dem Cryptography Module für maximale Sicherheit. ## Kernkomponenten ### PasswordHasher Service Sichere Passwort-Hashing und -Verifizierung mit automatischem Rehashing. ```php use App\Framework\Auth\PasswordHasher; use App\Framework\Cryptography\KeyDerivationFunction; $passwordHasher = new PasswordHasher( kdf: $keyDerivationFunction, defaultAlgorithm: 'argon2id', defaultSecurityLevel: PasswordHasher::LEVEL_STANDARD ); // Passwort hashen $hashedPassword = $passwordHasher->hash('userPassword123'); // Passwort verifizieren $isValid = $passwordHasher->verify('userPassword123', $hashedPassword); // Passwort-Stärke validieren $validation = $passwordHasher->validatePasswordStrength('userPassword123'); if (!$validation->isValid) { echo implode(', ', $validation->errors); } ``` ### HashedPassword Value Object Immutables Value Object für gehashte Passwörter mit Metadaten. ```php use App\Framework\Auth\HashedPassword; use App\Framework\Auth\PasswordStrength; // Aus DerivedKey erstellen $hashedPassword = HashedPassword::fromDerivedKey($derivedKey); // Eigenschaften abrufen $algorithm = $hashedPassword->getAlgorithm(); // 'argon2id' $parameters = $hashedPassword->getParameters(); // ['memory_cost' => 65536, ...] $strength = $hashedPassword->getStrength(); // PasswordStrength::STRONG $createdAt = $hashedPassword->getCreatedAt(); // DateTimeImmutable // Rehashing-Prüfung $needsRehash = $hashedPassword->needsRehash('argon2id', [ 'memory_cost' => 131072, // Höhere Sicherheitsanforderungen 'time_cost' => 6 ]); // Sicherheits-Bewertung $assessment = $hashedPassword->assessSecurity(); echo $assessment->getSummary(); // "Strong security with Argon2ID (2024 standards)" ``` ### AuthenticationService Zentrale Authentifizierungslogik mit erweiterten Sicherheitsfeatures. ```php use App\Framework\Auth\AuthenticationService; use App\Framework\Http\IpAddress; $authService = new AuthenticationService( passwordHasher: $passwordHasher, sessionIdGenerator: $sessionIdGenerator, repository: $authRepository ); // Benutzer authentifizieren $result = $authService->authenticate( identifier: 'user@example.com', password: 'userPassword123', ipAddress: IpAddress::from('192.168.1.1'), remember: true ); if ($result->isSuccess()) { $user = $result->getUser(); $session = $result->getSession(); $rememberToken = $result->getRememberToken(); // nullable } // Mit Session authentifizieren $result = $authService->authenticateWithSession( $sessionId, IpAddress::from('192.168.1.1') ); // Mit Remember Token authentifizieren $result = $authService->authenticateWithRememberToken( $tokenValue, IpAddress::from('192.168.1.1') ); ``` ### PasswordValidationResult Value Object Detaillierte Passwort-Validierungsergebnisse. ```php use App\Framework\Auth\PasswordValidationResult; $validation = $passwordHasher->validatePasswordStrength('weakpass'); // Validierungsstatus prüfen $isValid = $validation->isValid; // false $errors = $validation->errors; // ['Password must be at least 8 characters long'] $warnings = $validation->warnings; // ['Consider using more character types'] $score = $validation->strengthScore; // 45 $strength = $validation->strength; // PasswordStrength::WEAK // Sicherheitslevel prüfen $meetsMinimum = $validation->meetsMinimumRequirements(); // false $isRecommended = $validation->isRecommended(); // false // Zusammenfassung echo $validation->getSummary(); // "Password does not meet requirements: Password must be at least 8 characters long" // API-Response Format $apiResponse = $validation->toArray(); ``` ## Sicherheitsfeatures ### Rate Limiting & Account Lockout Schutz vor Brute-Force-Angriffen durch intelligente Rate-Limitierung. ```php // Automatisches Rate Limiting in AuthenticationService const MAX_LOGIN_ATTEMPTS = 5; const LOCKOUT_DURATION = 900; // 15 Minuten const RATE_LIMIT_WINDOW = 300; // 5 Minuten // Rate Limiting wird automatisch angewendet $result = $authService->authenticate($email, $password, $ipAddress); if ($result->isRateLimited()) { $retryAfter = $result->getRetryAfter(); echo "Rate limit exceeded. Retry after {$retryAfter} seconds."; } if ($result->isAccountLocked()) { $expiresAt = $result->getLockoutExpiresAt(); echo "Account locked until {$expiresAt->format('Y-m-d H:i:s')}"; } ``` ### Session-Sicherheit Sichere Session-Verwaltung mit IP-Tracking und automatischer Rotation. ```php // Sessions werden automatisch erstellt und verwaltet const SESSION_TIMEOUT = 3600; // 1 Stunde const REMEMBER_TOKEN_LENGTH = 32; // 256-bit Token // Session-Features: // - Automatische IP-Konsistenz-Prüfung // - Session-Timeout-Management // - Aktivitäts-Tracking // - Sichere Session-IDs über SessionIdGenerator ``` ### Token-Hashing mit Hash Value Object Sichere Token-Behandlung mit typisierter Hash-Verwaltung. ```php // Remember Tokens werden sicher gehasht private function hashToken(string $token): Hash { return Hash::sha256($token); } // Vorteile: // - Typsicherheit für Hash-Werte // - Explizite Algorithmus-Angabe (SHA-256) // - Timing-safe Vergleiche mit hash_equals() // - Framework-konsistente Hash-Behandlung // - Automatische Hash-Validierung ``` ### Passwort-Sicherheit Umfassende Passwort-Validierung und -Bewertung. ```php // Automatische Passwort-Stärke-Bewertung $validation = $passwordHasher->validatePasswordStrength($password); // Validierungsregeln: // - Minimale Länge (8+ Zeichen) // - Komplexitätsanforderungen (2+ Zeichentypen) // - Häufige Muster-Erkennung // - Sequenzielle Zeichen-Prüfung // - Exzessive Wiederholungen // Sichere Passwort-Generierung $securePassword = $passwordHasher->generateSecurePassword( length: 16, includeUppercase: true, includeLowercase: true, includeNumbers: true, includeSpecialChars: true, excludeChars: '0O1l' // Mehrdeutige Zeichen ausschließen ); ``` ## Integration mit Framework ### Abhängigkeiten Das Auth Module nutzt vorhandene Framework-Komponenten: - **Cryptography Module**: Für sichere Key Derivation Functions - **SessionId/SessionIdGenerator**: Für Session-Management - **IpAddress Value Object**: Für IP-basierte Sicherheitsfeatures - **Hash Value Object**: Für typisierte Hash-Operationen ### Repository Pattern Flexible Datenpersistierung durch Repository-Abstraktion. ```php interface AuthenticationRepository { public function findUserByIdentifier(string $identifier): ?User; public function findUserById(string $userId): ?User; public function updateUserPassword(string $userId, HashedPassword $password): bool; public function storeSession(AuthenticationSession $session): void; public function findSessionById(SessionId $sessionId): ?AuthenticationSession; public function updateSessionActivity(SessionId $sessionId, ?IpAddress $ipAddress): void; public function deleteSession(SessionId $sessionId): bool; public function deleteAllUserSessions(string $userId): void; public function storeRememberToken(RememberToken $token): void; public function findRememberToken(Hash $tokenHash): ?RememberToken; public function deleteRememberToken(Hash $tokenHash): bool; public function deleteAllUserRememberTokens(string $userId): void; public function getFailedLoginAttempts(string $userId): int; public function incrementFailedLoginAttempts(string $userId): void; public function clearFailedLoginAttempts(string $userId): void; public function getLastFailedAttemptTime(string $userId): ?\DateTimeImmutable; } ``` ## Best Practices ### Sichere Implementation ```php // ✅ Sensitive Parameter verwenden public function authenticate( string $identifier, #[SensitiveParameter] string $password, ?IpAddress $ipAddress = null ): AuthenticationResult // ✅ Automatisches Rehashing if ($this->passwordHasher->needsRehash($user->getHashedPassword())) { $newHash = $this->passwordHasher->hash($password); $this->repository->updateUserPassword($user->getId(), $newHash); } // ✅ Timing-safe Token-Vergleiche $tokenHash = $this->hashToken($tokenValue); $rememberToken = $this->repository->findRememberToken($tokenHash); ``` ### Error Handling ```php // ✅ Generische Fehlermeldungen für Sicherheit if (!$user || !$this->passwordHasher->verify($password, $user->getHashedPassword())) { return AuthenticationResult::failed('Invalid credentials'); } // ✅ Security Event Logging $this->recordSecurityEvent('authentication_failed', [ 'identifier' => $identifier, 'ip_address' => $ipAddress ? (string) $ipAddress : null, 'reason' => $reason ]); ``` ### Performance Optimierung ```php // ✅ Konfigurierbare Sicherheitslevel $passwordHasher = new PasswordHasher( kdf: $keyDerivationFunction, defaultAlgorithm: 'argon2id', defaultSecurityLevel: PasswordHasher::LEVEL_STANDARD // vs HIGH für höhere Sicherheit ); // ✅ Bulk-Operationen für bessere Performance $this->repository->deleteAllUserSessions($userId); $this->repository->deleteAllUserRememberTokens($userId); ``` ## Nächste Schritte - [ ] AuthenticationRepository Interface implementieren - [ ] Authentication Exceptions definieren - [ ] Unit Tests für alle Komponenten schreiben - [ ] Rate Limiting Service implementieren - [ ] Integration Tests für Authentication Flow - [ ] Performance Benchmarks für Passwort-Hashing