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

Php Authenticator Laravel Package

chillerlan/php-authenticator

PHP 8.4+ library to generate and validate HOTP (RFC 4226) and TOTP (RFC 6238) one-time passwords—Google Authenticator compatible. Includes Steam Guard server time sync (cURL) and constant-time encoding/hex helpers (Sodium or fallback).

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Modularity: The package is a self-contained, single-purpose library for TOTP/HOTP generation and verification, aligning well with Laravel’s modular architecture. It can be integrated as a standalone service without polluting core application logic.
  • Stateless Design: The package operates on secrets and time/counter inputs, making it stateless and easy to integrate with Laravel’s session/cookie-based auth systems.
  • Extensibility: Supports multiple algorithms (SHA1, SHA256, SHA512), modes (TOTP/HOTP/Steam/Battle.net), and customizable options (e.g., digits, period), allowing flexibility for future requirements.
  • Laravel Compatibility: Works seamlessly with Laravel’s dependency injection (via service container) and event-driven architecture (e.g., triggering 2FA during login).

Integration Feasibility

  • Low Coupling: The package has no Laravel-specific dependencies, reducing integration risk. It can be injected into Laravel services (e.g., AuthManager, Guard) via constructor injection.
  • Database Agnostic: Secrets can be stored in any Laravel-supported database (MySQL, PostgreSQL, etc.) or even cached (Redis) for performance.
  • QR Code Generation: Supports otpauth:// URI generation, which can be rendered as QR codes using Laravel’s Dingo/api or spatie/qr-code packages.
  • Event Hooks: Can be integrated with Laravel’s auth events (e.g., Attempting, Authenticated) to enforce 2FA flows.

Technical Risk

  • PHP 8.4+ Requirement: If the Laravel app uses PHP 8.2/8.3, this introduces a migration risk. Mitigation: Use a lower version (e.g., ^5.4) or upgrade PHP.
  • Sodium Extension Dependency: Requires ext-sodium for secure encoding. Fallback to paragonie/constant_time_encoding is provided but adds minor complexity.
  • Time Synchronization: For TOTP, server time accuracy is critical. Laravel’s Carbon can be used to ensure consistency.
  • Secret Storage: Secrets must be securely stored (e.g., encrypted in the database). Laravel’s Encrypter can help here.
  • HOTP Counter Management: Requires tracking counter values per user (e.g., in a sessions or users table). Laravel’s migrations can handle this.

Key Questions

  1. Use Case Priority:
    • Is TOTP (time-based) or HOTP (counter-based) the primary requirement? Steam/Battle.net modes are niche.
    • Are adjacent code windows (e.g., allowing ±1 code) needed?
  2. Secret Storage:
    • How will secrets be stored? Encrypted in the database? Cached?
    • Will secrets be rotated, and if so, how will the package handle this?
  3. Performance:
    • Will 2FA be rate-limited? The package itself is lightweight, but DB/caching layers may introduce latency.
  4. Fallback Mechanisms:
    • Should backup codes (e.g., printed during setup) be supported? This isn’t part of the package but is a common UX requirement.
  5. Testing:
    • How will time-based tests be mocked (e.g., for CI/CD)? Laravel’s Carbon can freeze time for testing.
  6. Compliance:
    • Does the app need to comply with standards like FIDO2 or RFC 6238? This package adheres to RFC 6238 but lacks FIDO2 support.

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Auth Systems: Integrates natively with Laravel’s Auth facade or custom guards (e.g., Auth::attempt() → trigger 2FA).
    • Events: Can listen to Attempting, Authenticated, or Failed events to inject 2FA logic.
    • Caching: Secrets/counters can be cached (Redis) for performance.
    • Queue Jobs: 2FA verification can be async (e.g., send SMS/email with OTP via queues).
  • Frontend:
    • QR code generation: Use spatie/qr-code to render otpauth:// URIs.
    • UI: Display OTP input fields during login (e.g., via Blade or Inertia.js).
  • Database:
    • Add otp_secret (string) and otp_counter (integer, for HOTP) to the users table.
    • Example migration:
      Schema::table('users', function (Blueprint $table) {
          $table->string('otp_secret')->nullable();
          $table->integer('otp_counter')->default(0);
      });
      

Migration Path

  1. Phase 1: Setup
    • Install the package:
      composer require chillerlan/php-authenticator
      
    • Add a 2fa column to the users table (see above).
    • Create a 2fa middleware to check for enabled 2FA and prompt for OTP.
  2. Phase 2: Integration
    • Extend Laravel’s AuthManager or create a custom TwoFactorGuard:
      use chillerlan\Authenticator\Authenticator;
      use chillerlan\Authenticator\AuthenticatorOptions;
      
      class TwoFactorGuard extends Guard {
          protected function authenticateUsingCredentials(array $credentials) {
              // ... existing logic ...
              if ($this->has2FA($user)) {
                  $otp = $this->getOTPInput(); // From request
                  $authenticator = new Authenticator(
                      new AuthenticatorOptions(['digits' => 6]),
                      $user->otp_secret
                  );
                  if (!$authenticator->verify($otp)) {
                      throw new AuthenticationException;
                  }
              }
          }
      }
      
    • Register the guard in AuthServiceProvider:
      $this->app['guard'] = function ($app) {
          return new TwoFactorGuard(...);
      };
      
  3. Phase 3: User Flow
    • Add routes/controllers for:
      • Enabling 2FA (generate QR code/secret).
      • Disabling 2FA (clear otp_secret).
      • Backup code generation (optional).
    • Example QR code generation:
      use chillerlan\Authenticator\Authenticator;
      use SimpleSoftwareIO\QrCode\Facades\QrCode;
      
      $authenticator = new Authenticator();
      $secret = $authenticator->createSecret();
      $uri = $authenticator->getUri('User Email', 'App Name');
      return QrCode::size(200)->generate($uri);
      

Compatibility

  • Laravel Versions: Compatible with Laravel 10+ (PHP 8.4+). For older versions, use ^5.4 of the package.
  • Package Dependencies:
    • ext-curl (optional, for Steam Guard time sync).
    • ext-sodium (recommended; fallback provided).
  • Database: Works with any Laravel-supported database. No schema changes beyond adding otp_secret/otp_counter.
  • Caching: Secrets/counters can be cached (e.g., Redis) to reduce DB load.

Sequencing

  1. Pre-requisite: Upgrade PHP to 8.4+ if not already done.
  2. Database: Run migrations to add 2FA columns.
  3. Backend:
    • Integrate the package into the auth flow.
    • Add middleware for 2FA checks.
  4. Frontend:
    • Add UI for OTP input and QR code display.
    • Style the 2FA setup/enable flow.
  5. Testing:
    • Write unit tests for Authenticator (mock time/counters).
    • Test edge cases (e.g., expired codes, wrong inputs).
  6. Deployment:
    • Roll out in stages (e.g., enable 2FA for admins first).
    • Monitor failure rates and latency.

Operational Impact

Maintenance

  • Package Updates: The package is actively maintained (last release: 2026-03-21). Minor updates (e.g., dependency patches) can be applied via Composer.
  • Secret Rotation:
    • Implement a rotate2FASecret() method in a Laravel command/service to regenerate secrets periodically.
    • Example:
      $authenticator = new Authenticator();
      $newSecret = $authenticator->createSecret();
      $user->update(['otp_secret' => $newSecret]);
      
  • Backup Codes: While not part of the package, consider adding a backup_codes JSON column to the users table for manual recovery.

Support

  • Troubleshooting:
    • Time Sync Issues: Ensure server time is accurate (use NTP). For TOTP, log getServertime() to debug.
    • Code Rejection: Verify digits, algorithm, and period settings match the authenticator app (e.g., Google Authenticator).
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope