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 verify HOTP (RFC 4226) and TOTP (RFC 6238) one-time passwords, compatible with Google Authenticator-style apps. Includes optional Steam Guard time sync plus constant-time encoding helpers for safer key handling.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Laravel Integration: The package is highly compatible with Laravel due to its PHP-centric design and lack of framework-specific dependencies. It can be seamlessly integrated into Laravel’s authentication stack (e.g., replacing or augmenting Laravel Fortify/Passport’s 2FA).
  • Modularity: The package follows a clean, interface-driven architecture (AuthenticatorInterface), making it easy to swap implementations (e.g., for testing or future upgrades).
  • RFC Compliance: Strict adherence to RFC 4226 (HOTP) and RFC 6238 (TOTP) ensures interoperability with standard-compliant authenticator apps (Google Authenticator, Authy, etc.).
  • Extensibility: Supports custom modes (Steam Guard, Battle.net) and algorithm flexibility (SHA1/SHA256/SHA512), allowing for future-proofing or niche use cases.

Integration Feasibility

  • Laravel-Specific Hooks: Can be integrated into:
    • Laravel Fortify: Custom 2FA verification logic in VerifyTwoFactorChallenge.
    • Laravel Sanctum/Passport: Pre-authentication middleware for API 2FA.
    • Laravel Sessions: Storing secrets in user table or encrypted sessions table.
  • Database Schema: Minimal changes required—only a secret (base32-encoded string) and optionally a counter (for HOTP) or last_used_at (for TOTP) field per user.
  • Caching: OTP verification is stateless (except for HOTP counters), so caching the Authenticator instance per request is efficient.

Technical Risk

Risk Area Mitigation Strategy
PHP 8.4 Dependency Laravel 10+ supports PHP 8.4; downgrade risk is low if using older Laravel.
Sodium Extension Fallback to paragonie/constant_time_encoding ensures compatibility.
Secret Storage Secrets must be base32-encoded and stored securely (e.g., encrypted DB field).
Time Sync (TOTP) useLocalTime option allows fallback to server time if client time is unreliable.
HOTP Counter Drift Requires careful DB design (e.g., auto-incrementing counter or manual updates).
Algorithm Downgrades SHA1 is deprecated; enforce SHA256/SHA512 via AuthenticatorOptions.

Key Questions

  1. Mode Selection:

    • Should the system default to TOTP (time-based) or support HOTP (counter-based) for offline use?
    • Recommendation: Default to TOTP; add HOTP as an optional mode for edge cases.
  2. Secret Storage:

    • Where will secrets be stored? (e.g., users table, Redis, or a dedicated otp_secrets table?)
    • Recommendation: Encrypted field in users table with a secret column (base32) and otp_mode (TOTP/HOTP).
  3. Verification Flow:

    • Should verification be synchronous (blocking) or asynchronous (e.g., queue-based for API calls)?
    • Recommendation: Synchronous for web; async for APIs with rate-limiting.
  4. Fallback Mechanisms:

    • How will the system handle failed verifications (e.g., rate-limiting, backup codes)?
    • Recommendation: Integrate with Laravel’s throttle middleware and add backup code support.
  5. Testing:

    • How will mock secrets be generated for unit tests?
    • Recommendation: Use Authenticator::createSecret() in tests with fixed time offsets.

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Fortify: Replace VerifyTwoFactorChallenge with custom logic using chillerlan/php-authenticator.
    • Sanctum/Passport: Add a TwoFactorGuard middleware to validate OTPs before issuing tokens.
    • Horizon/Queues: Offload OTP verification for APIs to avoid blocking requests.
  • Dependencies:
    • Required: ext-curl (for Steam Guard), ext-sodium (preferred) or paragonie/constant_time_encoding.
    • Optional: endroid/qr-code (for QR code generation in user onboarding).

Migration Path

  1. Phase 1: Setup

    • Add package to composer.json:
      "require": {
          "chillerlan/php-authenticator": "^5.4"
      }
      
    • Publish a migration to add secret and otp_mode fields to the users table:
      Schema::table('users', function (Blueprint $table) {
          $table->string('otp_secret')->nullable();
          $table->enum('otp_mode', ['totp', 'hotp'])->default('totp')->nullable();
          $table->integer('otp_counter')->nullable(); // For HOTP
      });
      
  2. Phase 2: User Onboarding

    • Create a 2FA setup route (e.g., /setup-2fa) that:
      • Generates a secret: $authenticator->createSecret().
      • Displays a QR code (using getUri()) and manual entry fallback.
      • Saves the secret to the user’s record.
  3. Phase 3: Verification Logic

    • Web (Fortify):
      public function verifyTwoFactorChallenge(Request $request)
      {
          $user = User::find($request->user());
          $authenticator = new Authenticator(
              new AuthenticatorOptions(['mode' => $user->otp_mode]),
              $user->otp_secret
          );
          if ($authenticator->verify($request->input('code'))) {
              // Success: regenerate session or issue token.
          }
          return back()->withErrors(['code' => 'Invalid OTP.']);
      }
      
    • API (Sanctum/Passport):
      public function authenticate(Request $request)
      {
          $user = User::find($request->user());
          $authenticator = new Authenticator(
              new AuthenticatorOptions(['mode' => $user->otp_mode]),
              $user->otp_secret
          );
          if (!$authenticator->verify($request->code)) {
              throw new \Illuminate\Auth\AuthenticationException;
          }
          return $this->createToken($user);
      }
      
  4. Phase 4: HOTP Support (Optional)

    • Extend the users table with otp_counter.
    • Update verification logic to pass the counter:
      $authenticator->verify($request->code, $user->otp_counter);
      $user->increment('otp_counter'); // After successful verification.
      

Compatibility

  • Laravel Versions: Works with Laravel 10+ (PHP 8.4+). For older versions, pin to ^5.3 (PHP 8.1+).
  • Authenticator Apps: Compatible with Google Authenticator, Authy, Microsoft Authenticator (TOTP) and Steam/Battle.net (custom modes).
  • Database: No schema locks; migrations are idempotent.

Sequencing

  1. Backward Compatibility:
    • Start with TOTP-only to minimize risk.
    • Add HOTP support in a later release if needed.
  2. Feature Flags:
    • Use Laravel’s config('features.2fa') to toggle 2FA during rollout.
  3. Monitoring:
    • Log verification failures to detect secret leaks or time sync issues.

Operational Impact

Maintenance

  • Dependencies:
    • Low: Only chillerlan/php-authenticator and optional QR libraries.
    • Updates: Monitor for PHP 8.5+ compatibility (e.g., curl_close() deprecation).
  • Secret Rotation:
    • Implement a manual rotation feature (e.g., /rotate-2fa-secret) to revoke compromised secrets.
    • Recommendation: Log secret changes and notify users via email.
  • Algorithm Security:
    • Deprecate SHA1 in AuthenticatorOptions via config:
      'auth' => [
          'otp' => [
              'algorithm' => 'SHA256', // Force SHA256/SHA512
          ],
      ],
      

Support

  • Common Issues:
    • Time Sync: Users in different time zones may see delays. Use useLocalTime: false and sync server time.
    • OTP Expiry: Default 30-second window may be too short; adjust period
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport