Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How can I integrate Google Authenticator with Laravel's two-factor authentication


How can I integrate Google Authenticator with Laravel's two-factor authentication


To integrate Google Authenticator with Laravel's two-factor authentication (2FA), the process involves setting up a Time-Based One-Time Password (TOTP) system following the RFC 6238 standard, which works through apps like Google Authenticator generating time-limited codes that users must provide along with their usual password. This enhances security by requiring a second factor that is accessible only through the user's device.

Overview of Two-Factor Authentication (2FA) in Laravel

Two-factor authentication adds an additional layer of security beyond just the password by requiring a code generated by an authenticator app. When integrating Google Authenticator, Laravel applications must manage secret keys for users, generate QR codes for easy setup, verify time-based codes during login, and handle enabling/disabling of 2FA.

Step 1: Setup Laravel Project

Start with a Laravel application (Laravel 6 to Laravel 12 are supported by major packages). Ensure user authentication is implemented using Laravel's built-in or custom system.

Step 2: Install Google2FA Package

Use the popular `antonioribeiro/google2fa-laravel` package which acts as a Laravel wrapper around the Google2FA PHP library. This library supports both HOTP and TOTP and handles QR code generation and code verification.

Install via Composer:


composer require pragmarx/google2fa-laravel

Publish configuration if needed and migrations.

Step 3: Database Preparation

Add a column to the users table to store the Google 2FA secret key, typically named `google2fa_secret`.

Create a migration:

php
Schema::table('users', function (Blueprint $table) {
    $table->string('google2fa_secret')->nullable();
});

This column stores the base32-encoded secret key shared between the server and the user's app.

Step 4: Update User Model

Update the User model to include the `google2fa_secret` field as fillable or guarded appropriately and hidden from JSON serialization:

php
protected $fillable = [
    'name', 'email', 'password', 'google2fa_secret',
];

protected $hidden = [
    'password', 'remember_token', 'google2fa_secret',
];

Step 5: Generate and Show QR Code for 2FA Setup

When the user opts to enable 2FA, generate a secret key and display a QR code for them to scan with Google Authenticator app.

In the controller handling 2FA setup:

php
use PragmaRX\Google2FAQRCode\Google2FA;

$google2fa = new Google2FA();

$secretKey = $google2fa->generateSecretKey();

$google2faUrl = $google2fa->getQRCodeUrl(
    config('app.name'), // Company or app name
    $user->email,
    $secretKey
);

Use a QR code package to render `$google2faUrl` on the setup page.

Save the `$secretKey` temporarily for verification after the user scans and inputs a code.

Step 6: Verify One-Time Password from the User

After the user scans the QR code and enters the code from their Google Authenticator app, verify the code:

php
$valid = $google2fa->verifyKey($secretKey, $request->input('one_time_password'));

if ($valid) {
    $user->google2fa_secret = $secretKey;
    $user->save();
    // 2FA enabled successfully
} else {
    // Show error, invalid code
}

Only save the secret key after successful validation to prevent invalid keys being stored.

Step 7: Enforce Two-Factor Authentication on Login

Modify the login flow to prompt for the 2FA code if it's enabled for the user.

The flow would be:

1. User submits email and password.
2. Password is validated.
3. If user has `google2fa_secret` set, show a form to input the current time-based code.
4. Verify the code:

php
$google2fa->verifyKey($user->google2fa_secret, $request->input('one_time_password'));

5. On success, complete login and store 2FA session flag.
6. On failure, reject login or lock out if multiple failures.

Step 8: Protect Routes with 2FA Middleware

Create middleware to check if the logged-in user has completed 2FA verification. Redirect unauthenticated or non-verified users to the 2FA code input form.

Example middleware:

php
public function handle($request, Closure $next)
{
    if (auth()->check() && auth()->user()->google2fa_secret && !session('2fa_verified')) {
        return redirect('2fa/verify');
    }
    return $next($request);
}

Step 9: Additional Features

- Provide options to disable 2FA after re-authentication.
- Use throttling on 2FA code input attempts to prevent brute force.
- Provide backup codes or alternative access methods in case the user loses their device.
- Notify the user when 2FA settings change.
- Optionally, require 2FA on sensitive operations beyond login.

Security Considerations

- Encrypt the secret keys stored in the database or use a dedicated encryption mechanism.
- Use HTTPS to secure all authentication communications.
- Implement rate limiting on verification attempts.
- Ensure proper session handling to avoid session fixation or hijacking.

Summary

The integration process involves installing a Google2FA package, extending the User model and database for secrets, generating secrets and QR codes for users to scan, verifying TOTP codes on setup and login, and enforcing 2FA via middleware. This makes Laravel applications much more secure by requiring a second factor that is generated on the user's device and valid only for a short time period. This method supports offline code generation and is widely adopted for many systems.

This approach works across Laravel versions and can be enhanced with packages such as `laragear/two-factor` for additional flexibility and management. Using these tools, developers can implement seamless and strong two-factor authentication with Google Authenticator in Laravel applications.

The detailed implementation involves configuration, database changes, authentication flow modifications, user interface for setup and code entry, and middleware to enforce the policy, ultimately improving the security posture of the app significantly.