Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do I generate the QR code for Google Authenticator in Laravel


How do I generate the QR code for Google Authenticator in Laravel


To generate a QR code for Google Authenticator in Laravel, you can use the `pragmarx/google2fa-laravel` package. Here are the steps:

Step 1: Install the Package

1. Install the Package:

bash
   composer require pragmarx/google2fa-laravel
   

Step 2: Configure the Package

1. Publish Configuration:

bash
   php artisan vendor:publish --provider="PragmaRX\Google2FALaravel\ServiceProvider"
   

Step 3: Generate the QR Code

1. Generate QR Code:

php
   $google2fa = app('pragmarx.google2fa');
   $qrCodeUrl = $google2fa->getQRCodeInline(
       'Your App Name',
       $user->email,
       $google2fa->generateSecretKey()
   );
   

Step 4: Display the QR Code

1. Display QR Code:

php
   <img src="{{ $qrCodeUrl }}" alt="QR Code">
   

Step 5: Verify the QR Code

1. Verify QR Code:

php
   $google2fa = app('pragmarx.google2fa');
   $valid = $google2fa->verifyKey($user->google2fa_secret, $request->input('one_time_password'));
   

Step 6: Handle Verification

1. Handle Verification:

php
   if ($valid) {
       // 2FA code is valid, proceed with login
       return redirect()->route('admin.dashboard');
   } else {
       // Invalid 2FA code, redirect back with an error message
       return redirect()->route('2fa')->withErrors(['one_time_password' => 'Invalid OTP code']);
   }
   

By following these steps, you can generate and display the QR code for Google Authenticator in your Laravel application.

Citations:
[1] https://dan.hersam.com/tools/gen-qr-code.php
[2] https://github.com/brandonlim-hs/example-laravel-google-authenticator
[3] https://stackoverflow.com/questions/34520928/how-to-generate-a-qr-code-for-google-authenticator-that-correctly-shows-issuer-d
[4] https://stackoverflow.com/questions/76985600/laravel-google-authenticator-2fa-verify-successful-but-unable-to-redirect-to-h
[5] https://www.itsolutionstuff.com/post/laravel-google-2fa-authentication-tutorial-exampleexample.html