Overview
SAPFIAI implements two-factor authentication (2FA) using time-based codes sent via email. This adds an additional security layer to the authentication process.TwoFactorService
TheTwoFactorService handles all 2FA operations including code generation, validation, and delivery.
Location: src/Infrastructure/Services/TwoFactorService.cs:17
Dependencies
Configuration
Configure 2FA settings inappsettings.json or environment variables:
Two-Factor Flow
1. User Login with 2FA Enabled
When a user with 2FA enabled attempts to login:2. Generate and Send 2FA Code
The system automatically generates and sends a 6-digit code:- Generates cryptographically secure 6-digit code
- Stores code in memory cache with expiration
- Sends code via email using
IEmailService - In development: Shows code in console logs
3. User Submits Verification Code
4. Validate 2FA Code
- Constant-time comparison prevents timing attacks
- Code retrieved from memory cache
- Automatic expiration after configured time
- Case and whitespace handling
5. Clear 2FA Code
After successful validation or on failure:Enabling 2FA for Users
Enable 2FA Endpoint
src/Web/Endpoints/Authentication.cs:212
Check 2FA Status
JWT Integration
When 2FA is pending, the JWT token includes a special claim:API Endpoints
Enable Two-Factor Authentication
Verify Two-Factor Code
Complete Authentication Flow
Client-Side Implementation Example
Security Considerations
Code Generation
- Uses
RandomNumberGeneratorfor cryptographic randomness - 6-digit codes provide 1,000,000 possible combinations
- Short expiration time (10 minutes) limits brute-force attempts
Code Validation
- Constant-time comparison prevents timing attacks
- Code is removed from cache after validation
- No indication whether code was wrong or expired
Storage
- Codes stored in memory cache (not database)
- Automatic expiration through cache policy
- Cleared immediately after use
Rate Limiting
Consider implementing rate limiting on 2FA endpoints:Development vs Production
Development Mode
- Codes logged to console for easy testing
- Email failures don’t block authentication
- Shorter expiration times acceptable
Production Mode
- Email delivery required
- No console logging of codes
- Consider SMS or authenticator app alternatives
- Monitor failed 2FA attempts
Audit Logging
All 2FA events are logged to audit logs:Implementation Details
File locations:- TwoFactorService:
src/Infrastructure/Services/TwoFactorService.cs:17 - Enable 2FA Command:
src/Application/Users/Commands/EnableTwoFactor/ - Validate 2FA Command:
src/Application/Users/Commands/ValidateTwoFactor/ - Verify Endpoint:
src/Web/Endpoints/Authentication.cs:126 - Enable Endpoint:
src/Web/Endpoints/Authentication.cs:212