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

Two Factor Laravel Package

laragear/two-factor

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require laragear/two-factor
    php artisan two-factor:install
    php artisan migrate
    
  2. Configure User Model: Add the contract and trait to your User model:

    use Laragear\TwoFactor\TwoFactorAuthentication;
    use Laragear\TwoFactor\Contracts\TwoFactorAuthenticatable;
    
    class User extends Authenticatable implements TwoFactorAuthenticatable
    {
        use TwoFactorAuthentication;
    }
    
  3. First Use Case: Integrate the Auth2FA facade into your login logic:

    use Laragear\TwoFactor\Facades\Auth2FA;
    
    public function login(Request $request)
    {
        $attempt = Auth2FA::attempt($request->only('email', 'password'));
        return $attempt ? redirect()->home() : back()->withErrors(['email' => 'Invalid credentials']);
    }
    

Implementation Patterns

Workflows

  1. Enabling 2FA:

    • Generate a shared secret and QR code for the user:
      $secret = auth()->user()->createTwoFactorAuth();
      return view('2fa.setup', ['qr_code' => $secret->toQr()]);
      
    • Confirm with a TOTP code:
      $confirmed = auth()->user()->confirmTwoFactorAuth($request->code);
      
  2. Login Flow:

    • Use Auth2FA::attempt() to handle credentials and 2FA validation in one call.
    • Customize the 2FA flow with fluent methods:
      Auth2FA::message('2FA required')
             ->input('two_factor_code')
             ->attempt($credentials);
      
  3. Recovery Codes:

    • Display codes after enabling 2FA:
      return auth()->user()->getRecoveryCodes();
      
    • Regenerate codes if needed:
      auth()->user()->generateRecoveryCodes();
      

Integration Tips

  • Middleware: Protect routes with 2fa.enabled to enforce 2FA:
    Route::get('/dashboard', function () {})->middleware('2fa.enabled');
    
  • Events: Listen for 2FA lifecycle events (e.g., TwoFactorEnabled) to trigger notifications or logs.
  • Customization: Override default views or messages by publishing the package’s assets:
    php artisan vendor:publish --provider="Laragear\TwoFactor\TwoFactorServiceProvider"
    

Gotchas and Tips

Pitfalls

  1. Session Handling:

    • Credentials are flashed to the session during 2FA validation. Ensure your session driver is configured correctly (e.g., file, database, or redis).
    • Clear flashed data after login to avoid reuse:
      session()->forget('_2fa_login');
      
  2. Recovery Codes:

    • Users can be locked out if all recovery codes are used and 2FA is not disabled. Provide a fallback (e.g., admin recovery or email verification).
    • Default codes are 8 characters long. Customize with generateRecoveryCodesUsing() if needed.
  3. Time Synchronization:

    • TOTP codes rely on device time. Users may fail validation if their device clock is incorrect. Guide them to sync their device time.

Debugging

  • Failed 2FA Codes:

    • Verify the user’s authenticator app is generating codes for the correct URI (check toUri() output).
    • Ensure the user’s device timezone matches the server’s timezone (or use UTC for consistency).
  • Middleware Bypass:

    • Middleware (2fa.enabled, 2fa.confirm) only applies to models implementing TwoFactorAuthenticatable. Exclude non-2FA users explicitly:
      if (!auth()->user() instanceof TwoFactorAuthenticatable) {
          return redirect()->route('home');
      }
      

Extension Points

  1. Custom Validation:

    • Extend the TwoFactorAuthentication trait to add logic (e.g., rate-limiting 2FA attempts):
      public function confirmTwoFactorAuth($code)
      {
          if ($this->failedAttempts() >= 5) {
              throw new \Exception('Too many attempts');
          }
          return parent::confirmTwoFactorAuth($code);
      }
      
  2. Safe Devices:

    • Bypass 2FA for trusted devices using cookies. Customize the cookie name or logic in the TwoFactorAuthentication trait:
      protected function isSafeDevice(): bool
      {
          return request()->cookie('trusted_device') === 'true';
      }
      
  3. QR Code Customization:

    • Modify the QR code appearance by publishing the package’s views and editing the SVG template:
      php artisan vendor:publish --tag=two-factor-views
      
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.
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope