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 Totp Laravel Package

scheb/2fa-totp

TOTP (Time-based One-Time Password) provider for the scheb TwoFactorBundle, enabling app-based 2FA with authenticator codes. Part of the scheb/2fa project (read-only mirror); see main repo/docs for setup.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps for Laravel Integration

  1. Install Dependencies: Require the package and Symfony bridge components:

    composer require scheb/2fa-totp scheb/2fa-bundle symfony/http-foundation symfony/routing
    
  2. Publish Configuration: Copy the bundle’s configuration to Laravel’s config:

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

    Merge the published config/2fa.php with your existing config.

  3. Set Up Database: Run migrations to add TOTP fields to your users table:

    php artisan vendor:publish --provider="Scheb\TwoFactorBundle\SchebTwoFactorBundle" --tag="migrations"
    php artisan migrate
    
  4. First Use Case: Enable TOTP for a User Generate a secret and QR code for a user in a controller:

    use Scheb\TwoFactorBundle\Security\TwoFactorAuthenticatorInterface;
    
    public function enableTotp(TwoFactorAuthenticatorInterface $twoFactor)
    {
        $user = auth()->user();
        $secret = $twoFactor->generateSecret();
        $qrCodeUrl = $twoFactor->generateQrCodeUrl($user->email, $secret);
    
        // Store secret in DB (e.g., $user->totp_secret = $secret)
        $user->save();
    
        return view('totp.setup', compact('qrCodeUrl'));
    }
    
  5. Verify TOTP in Login Flow Add middleware to check TOTP on protected routes:

    // app/Http/Kernel.php
    protected $routeMiddleware = [
        'verify.totp' => \App\Http\Middleware\VerifyTotp::class,
    ];
    

    Create VerifyTotp middleware to validate TOTP codes:

    use Scheb\TwoFactorBundle\Security\TwoFactorAuthenticatorInterface;
    
    public function handle(Request $request, Closure $next, TwoFactorAuthenticatorInterface $twoFactor)
    {
        if (!$request->has('totp_code')) {
            return redirect()->route('login.totp');
        }
    
        $user = auth()->user();
        if (!$twoFactor->checkCode($user, $request->input('totp_code'))) {
            return back()->withErrors(['totp' => 'Invalid code']);
        }
    
        return $next($request);
    }
    

Implementation Patterns

Core Workflows

  1. TOTP Setup Flow:

    • Generate Secret: Use TwoFactorAuthenticatorInterface::generateSecret().
    • QR Code: Generate with TwoFactorAuthenticatorInterface::generateQrCodeUrl().
    • Store Secret: Save to user model (e.g., totp_secret, totp_algorithm).
    • User Verification: Prompt user to enter codes from their authenticator app.
  2. Login with TOTP:

    • Step 1: Authenticate with username/password (standard Laravel flow).
    • Step 2: Redirect to TOTP input if enabled:
      if ($user->hasTotpEnabled()) {
          return redirect()->route('login.totp', ['user' => $user]);
      }
      
    • Step 3: Validate TOTP code via middleware or controller:
      $twoFactor->checkCode($user, $request->totp_code);
      
  3. Backup Codes: Generate and store backup codes for recovery:

    $backupCodes = $twoFactor->generateBackupCodes();
    $user->backup_codes = json_encode($backupCodes);
    $user->save();
    

Integration Tips

  • Laravel Auth Integration: Extend Laravel’s AuthManager to support TOTP:

    // app/Providers/AuthServiceProvider.php
    public function boot()
    {
        $this->app['auth']->viaRequest('totp', function ($request) {
            return $this->authenticateTotp($request);
        });
    }
    
  • Middleware for Protected Routes: Use middleware to enforce TOTP on sensitive routes:

    Route::middleware(['auth', 'verify.totp'])->group(function () {
        // Admin dashboard, financial actions, etc.
    });
    
  • Custom Templates: Override Twig templates by publishing assets:

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

    Then customize in resources/views/vendor/two_factor/.

  • Event Listeners: Listen for TOTP events to log or notify:

    // app/Providers/EventServiceProvider.php
    protected $listen = [
        'Scheb\TwoFactorBundle\Security\TwoFactorEvent::TOTP_VERIFIED' => [
            \App\Listeners\LogTotpVerification::class,
        ],
    ];
    
  • Testing: Mock TOTP verification in tests:

    $twoFactor = $this->createMock(TwoFactorAuthenticatorInterface::class);
    $twoFactor->method('checkCode')->willReturn(true);
    $this->app->instance(TwoFactorAuthenticatorInterface::class, $twoFactor);
    

Gotchas and Tips

Pitfalls

  1. Symfony-Laravel Abstraction Gaps:

    • Issue: Symfony’s EventDispatcher or HttpFoundation may not work out-of-the-box.
    • Fix: Use Laravel’s Events or wrap Symfony components:
      use Symfony\Component\EventDispatcher\EventDispatcher as SymfonyDispatcher;
      $dispatcher = new SymfonyDispatcher();
      $dispatcher->addListener('security.totp.verified', function ($event) {
          event(new \App\Events\TotpVerified($event->getUser()));
      });
      
  2. Database Schema Mismatches:

    • Issue: The bundle expects specific fields (e.g., secret, algorithm). Laravel’s migrations may conflict.
    • Fix: Customize migrations or use a trait:
      use Scheb\TwoFactorBundle\Model\TwoFactorUserInterface;
      
      class User extends Authenticatable implements TwoFactorUserInterface
      {
          // Implement required methods
      }
      
  3. Clock Skew in TOTP:

    • Issue: TOTP codes expire based on server time. Device clock drift can cause failures.
    • Fix: Allow a small time window (e.g., ±1 minute) in verification:
      $twoFactor->checkCode($user, $code, 60); // 60-second tolerance
      
  4. Middleware Order:

    • Issue: TOTP middleware must run after auth but before route handling.
    • Fix: Place middleware in Kernel.php with correct priority:
      protected $middlewareGroups = [
          'web' => [
              // ...
              \App\Http\Middleware\VerifyTotp::class,
          ],
      ];
      
  5. Backup Code Security:

    • Issue: Backup codes are often stored in plaintext.
    • Fix: Encrypt them in the database:
      $user->backup_codes = encrypt(json_encode($backupCodes));
      

Debugging Tips

  • Enable Debug Logging: Configure the bundle to log TOTP events:

    // config/2fa.php
    'debug' => env('APP_DEBUG', false),
    'log' => [
        'enabled' => true,
        'path' => storage_path('logs/totp.log'),
    ],
    
  • Test with Mock Time: Simulate TOTP code generation for testing:

    $twoFactor->setTimeProvider(new \Scheb\TwoFactorBundle\Security\TimeProvider(1234567890));
    
  • Validate QR Codes: Use tools like Google Authenticator to test QR generation.

Extension Points

  1. Custom TOTP Algorithms: Extend the authenticator to support additional algorithms:

    use Scheb\TwoFactorBundle\Security\TwoFactorAuthenticatorInterface;
    
    class CustomTotpAuthenticator implements TwoFactorAuthenticatorInterface
    {
        public function checkCode($user, $code, $timeWindow = 0)
        {
            // Custom logic (e.g., SHA-256 instead of SHA-1)
        }
    }
    
  2. Dynamic Secret Rotation: Implement a cron job to rotate secrets periodically:

    // app/Console/Commands/RotateTotpSecrets.php
    public function handle()
    {
        $users = User::whereNotNull('totp_secret')->get();
        foreach ($users as $user) {
            $newSecret = $this->twoFactor->generateSecret();
            $user->totp_secret = $newSecret;
            $user->save();
            // Send notification to user
        }
    }
    
  3. Hardware Key Support:

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.
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
baks-dev/finances
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle