Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

2Fa Backup Code Laravel Package

scheb/2fa-backup-code

Adds backup code support to scheb/2fa for Symfony apps. Generate, store, and validate one-time recovery codes so users can access accounts when they lose their 2FA device. Integrates with existing 2FA flows and user providers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require scheb/2fa-backup-code
    

    Ensure scheb/2fa-bundle is also installed (this package extends it).

  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="Scheb\TwoFactorBundle\SchebTwoFactorBundle" --tag=config
    

    Update config/scheb_two_factor.php to enable backup codes:

    'backup_codes' => [
        'enabled' => true,
        'count' => 10, // Default number of backup codes per user
    ],
    
  3. First Use Case Trigger backup code generation for a user during registration or profile setup:

    use Scheb\TwoFactorBundle\Model\BackupCodeManagerInterface;
    
    $backupCodeManager = $this->get('scheb_two_factor.backup_code_manager');
    $backupCodes = $backupCodeManager->generateBackupCodes($user);
    $backupCodeManager->saveBackupCodes($user, $backupCodes);
    

Implementation Patterns

Workflow: User Onboarding

  1. Generate & Store Codes

    // Generate and save codes in a single step
    $backupCodeManager->generateAndSaveBackupCodes($user);
    
  2. Display to User Render the codes in a secure UI (e.g., masked or QR-encoded):

    {% for code in user.backupCodes %}
        {{ code.code }} {# Display or mask as needed #}
    {% endfor %}
    
  3. Revoke Codes

    $backupCodeManager->revokeBackupCodes($user);
    

Integration with Authentication

  • Backup Code Validation Extend the login logic to accept backup codes when 2FA fails:

    use Scheb\TwoFactorBundle\Security\TwoFactorAuthenticator;
    
    $authenticator = $this->get(TwoFactorAuthenticator::class);
    if (!$authenticator->authenticate($request, $user)) {
        $backupCode = $request->input('backup_code');
        if ($backupCodeManager->consumeBackupCode($user, $backupCode)) {
            // Grant access
        }
    }
    
  • Event Listeners Listen for scheb_two_factor.backup_code_generated to log or notify admins:

    public function handleBackupCodeGenerated(BackupCodeGeneratedEvent $event) {
        \Log::info("Backup codes generated for user: {$event->user->id}");
    }
    

Database Considerations

  • Custom Storage Override the default storage (e.g., database) by implementing BackupCodeStorageInterface:
    class CustomBackupCodeStorage implements BackupCodeStorageInterface {
        public function save($user, array $codes) { /* ... */ }
        public function load($user) { /* ... */ }
        public function consume($user, $code) { /* ... */ }
    }
    
    Register it in config/scheb_two_factor.php:
    'backup_codes' => [
        'storage' => CustomBackupCodeStorage::class,
    ],
    

Gotchas and Tips

Pitfalls

  1. Backup Code Consumption

    • Codes are single-use by default. Consumed codes are automatically revoked.
    • Fix: Implement BackupCodeStorageInterface to customize behavior (e.g., allow reuse).
  2. Security Risks

    • Backup codes in logs: Avoid logging raw codes. Use a masked format (e.g., ****-****-1234).
    • Exposure in templates: Never render codes in production HTML. Use a secure download or masked display.
  3. Database Migrations

    • The package expects a backup_codes table. If using a custom storage, ensure migrations align with your schema.

Debugging

  • Missing Backup Codes Verify the backup_codes config is enabled and the storage service is bound:

    php artisan config:clear
    php artisan cache:clear
    
  • Codes Not Consuming Check for:

    • Case sensitivity in code validation.
    • Storage layer errors (e.g., database transactions).

Extension Points

  1. Custom Code Generation Override the default generator (e.g., for alphanumeric codes):

    $backupCodeManager->setBackupCodeGenerator(new CustomBackupCodeGenerator());
    
  2. Rate Limiting Limit backup code consumption attempts to prevent brute force:

    $backupCodeManager->setRateLimiter(new BackupCodeRateLimiter(5, 60)); // 5 attempts/minute
    
  3. Multi-Factor Backup Combine with other backup methods (e.g., email recovery) by extending the authenticator:

    class MultiFactorAuthenticator extends TwoFactorAuthenticator {
        public function authenticate(Request $request, UserInterface $user) {
            if ($this->isBackupCodeRequest($request)) {
                return $this->authenticateWithBackupCode($request, $user);
            }
            return parent::authenticate($request, $user);
        }
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky