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 Trusted Device Laravel Package

scheb/2fa-trusted-device

Adds trusted device support to scheb/2fa so users can skip 2FA on recognized devices for a set time. Stores trust tokens in cookies and persistence, with configurable lifetimes and validation, improving UX without removing 2FA security.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require scheb/2fa-trusted-device
    

    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 trusted devices:

    'trusted_device' => [
        'enabled' => true,
        'cookie_name' => '2fa_trusted_device',
        'cookie_lifetime' => 30, // days
        'ip_check' => true,      // verify IP consistency
        'user_agent_check' => true,
    ],
    
  3. First Use Case Trigger the trusted device flow in your login controller:

    use Scheb\TwoFactorBundle\Security\TwoFactorAuthenticator;
    
    public function login(Request $request, TwoFactorAuthenticator $twoFactor)
    {
        if ($twoFactor->isTrustedDeviceEnabled() && $twoFactor->isTrustedDevice($request)) {
            // Skip 2FA for trusted devices
            return redirect()->intended('/dashboard');
        }
        // Proceed with 2FA or normal login
    }
    

Implementation Patterns

Workflow Integration

  1. Login Flow

    • Use middleware to check for trusted devices before 2FA:
      public function handle($request, Closure $next)
      {
          if ($request->user() && $this->twoFactor->isTrustedDeviceEnabled()) {
              if ($this->twoFactor->isTrustedDevice($request)) {
                  return $next($request);
              }
              // Redirect to 2FA or mark as untrusted
          }
          return $next($request);
      }
      
  2. Trusted Device Management

    • Mark a device as trusted (after successful 2FA):
      $twoFactor->trustDevice($request);
      
    • Revoke trust (e.g., on password change or suspicious activity):
      $twoFactor->revokeTrustedDevice($request);
      
  3. Conditional Logic

    • Combine with scheb/2fa-bundle features:
      if ($twoFactor->isTrustedDevice($request) || $twoFactor->isTwoFactorAuthEnabled($request->user())) {
          // Handle 2FA or trusted flow
      }
      

Common Use Cases

  • Admin Panels: Skip 2FA for trusted devices to reduce friction.
  • API Tokens: Integrate with Sanctum/Passport to auto-trust devices for API clients.
  • Multi-Tenant Apps: Extend isTrustedDevice() to include tenant-specific checks.

Gotchas and Tips

Pitfalls

  1. Cookie Security

    • Ensure SameSite and Secure flags are set in your web server config for the 2fa_trusted_device cookie.
    • Fix: Add to app/Http/Middleware/TrustProxies.php:
      $cookie->setSecure(true);
      $cookie->setSameSite('Lax');
      
  2. IP/User-Agent Mismatches

    • If ip_check or user_agent_check is true, revoking trust may occur unexpectedly (e.g., VPN changes, device updates).
    • Workaround: Temporarily disable checks during testing:
      $twoFactor->setTrustedDeviceConfig(['ip_check' => false]);
      
  3. Session Conflicts

    • Trusted devices rely on cookies. If using session-based auth (e.g., session()->put()), ensure cookies are not cleared prematurely.

Debugging

  • Check Trusted Status:
    $twoFactor->isTrustedDevice($request); // Returns bool
    $twoFactor->getTrustedDeviceData($request); // Returns array (IP, user-agent, etc.)
    
  • Log Trusted Device Events:
    $twoFactor->onTrustedDeviceTrusted(function ($request) {
        \Log::info('Device trusted', ['ip' => $request->ip()]);
    });
    

Extension Points

  1. Custom Trust Logic Override the isTrustedDevice() check in a service:

    public function isTrustedDevice(Request $request)
    {
        if ($this->customCondition($request)) {
            return true;
        }
        return parent::isTrustedDevice($request);
    }
    
  2. Database Backend The package uses cookies by default. For persistence, extend the TrustedDeviceStorageInterface:

    class DatabaseTrustedDeviceStorage implements TrustedDeviceStorageInterface
    {
        public function store($userId, $data)
        {
            DB::table('trusted_devices')->updateOrInsert(
                ['user_id' => $userId],
                ['data' => $data]
            );
        }
        // Implement other methods...
    }
    
  3. Multi-Factor Trust Combine with other packages (e.g., laravel-notifiable) to send notifications when a new device is trusted:

    $twoFactor->onTrustedDeviceTrusted(function ($request) use ($user) {
        $user->notify(new DeviceTrusted($request->ip()));
    });
    
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.
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
spatie/mailcoach-vapor