2FA or Two Factor Authentication is a way of adding additional security to your account. The first “factor” is your usual password that is standard for an account, the second is a code retrieved from an external device such as a smartphone, or a program on your computer.
In simple words, when you log in to your account using your password and username or email, an extra security code is asked; i.e. a piece of private information which only and only you should know.
Lots of users, clients demand this type of service on their website. PayPal, Facebook, eBay, Yahoo, and many other websites support two-factor authentication nowadays.
The easiest and the fastest way to enable Two Factor Authentication on your website is to use Google Authenticator (Mobile App), which provides two-factor authentication for Google account logins, as well as other websites.
After creating a login and register for users we need to generate secret keys. These keys must be different for each user and it needs to be stored into the database on each user registration.
Step 1: First, to use two-factor authentication we need the google2fa package in our project.
Install the google2fa package with composer
composer require pragmarx/google2fa
You can also use BaconQrCode package for Inline QR codes.
Step 2: Create a registration page with basic details as per your requirements.
Step 3: Generate the secret key and store it along with the other user data into the database. The secret key is different for each user.
use PragmaRX\Google2FA\Google2FA; $google2fa = new Google2FA(); $google2fa_secret = $google2fa->generateSecretKey();
Step 4: Generate the QR code URL with the secret key and user data to link your website to the application.
$QRcodeURL = $google2fa->getQRCodeGoogleUrl( "My Website", $user->email, $user->google2fa_secret );
Step 5: Display the QR code using the generated URL.
<img src="<?php echo $QRcodeURL; ?>" />
Step 6: Now, download the Google Authenticator App according to your mobile platform and begin.
In order to connect with the website, the user would have to “scan the QR code” OR enter the “secret code” into the Google Authenticator App. After that, the user will be shown a 6-digit PIN code that is valid for 30 seconds and that needs to be entered in the form in order to be authenticated.
here, I have added my demo website’ QR code.
Step 7: Now validate the data that has been entered in the form, with the database.
$secret = $_POST['secret']; $valid = $google2fa->verifyKey($user->google2fa_secret, $secret);
Hope this was helpful!
checkout our Best laravel packages to help you extend your project’s functionalities easily.