What is 2FA?
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.
Where to start?
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.
1. Time-based One Time Password (TOTP)
2. HMAC-Based One-time Password (HOTP).
Implementation of Two Factor Authentication in PHP
After creating login and register for users we need to generate secret keys. This keys must be different for each user and it needs to be stored into the database on each user registration.
1. First, to use two-factor authentication we need 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.
2. Create a registration page with basic details as per your requirements.
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.
$google2fa = new Google2FA();
$google2fa_secret = $google2fa->generateSecretKey();
4. Generate QR code URL with the secret key and user data to link your website to the application.
$QRcodeURL = $google2fa->getQRCodeGoogleUrl(
Image source: Google
5. Display the QR code using the generated URL.
<img src="<?php echo $QRcodeURL; ?>" />
6. Now, download the Google Authenticator App according to your mobile platform and begin.
Image source: Google
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.
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);