phpgangsta/googleauthenticator

repository·master·Indexed 25 days ago

https://github.com/phpgangsta/googleauthenticator

A PHP implementation of the TOTP (Time-based One-Time Password) algorithm (RFC6238) for 2-factor authentication with the Google Authenticator mobile app. The PHPGangsta_GoogleAuthenticator class provides functionality to generate secrets, create QR-Code URLs, generate current codes, and verify codes with configurable clock tolerance.

Tokens
625
Snippets
3
Records
3
Agent score
31%

What's inside phpgangsta-googleauthenticator

  1. Install Google Authenticator via Composer

    master

    To install the library, use Composer from your project's root directory. Composer will handle the installation and provide autoloading for the library.

    After installation, include the Composer autoloader at the top of your PHP file to make the PHPGangsta_GoogleAuthenticator class available.

    composer install
    require_once __DIR__ . '/../vendor/autoload.php';
  2. Use the Google Authenticator PHP class

    master

    The PHPGangsta_GoogleAuthenticator class implements TOTP (RFC6238) to facilitate 2-factor authentication. It provides methods to:

    • Generate a new secret.
    • Generate a QR-Code URL for scanning with the Google Authenticator app.
    • Generate a current code.
    • Verify a provided code against a secret.

    Security Note: To prevent replay attacks, ensure that used codes cannot be reused. To prevent brute-force attacks, implement rate limiting (e.g., limiting verification attempts per IP address).

    <?php
    require_once 'PHPGangsta/GoogleAuthenticator.php';
    
    $ga = new PHPGangsta_GoogleAuthenticator();
    $secret = $ga->createSecret();
    
    // Generate QR Code URL
    $qrCodeUrl = $ga->getQRCodeGoogleUrl('Blog', $secret);
    
    // Generate and verify a code
    $oneCode = $ga->getCode($secret);
    $checkResult = $ga->verifyCode($secret, $oneCode, 2); // 2 = 2*30sec clock tolerance
    
    if ($checkResult) {
        echo 'OK';
    } else {
        echo 'FAILED';
    }
  3. Verify a TOTP code with clock tolerance

    master

    Use the verifyCode method to validate a user-provided code.

    Signature: $ga->verifyCode($secret, $code, $discrepancy)

    • $secret: The secret string generated for the user.
    • $code: The 6-digit code provided by the user.
    • $discrepancy: (Integer) The number of 30-second intervals of clock tolerance allowed. For example, a value of 2 allows for a window of 2 intervals before and after the current time to account for clock drift.
    $checkResult = $ga->verifyCode($secret, $oneCode, 2); // 2 = 2*30sec clock tolerance