Two-factor authentication (2FA) is considered the most secure way to protect online accounts. It protects user accounts with one-time codes that are usually delivered to the user with a 2FA application or text message. Big companies, such as Google, Facebook and Microsoft, already support 2FA, and it continues to gain more support on smaller websites too. This time we will see what it takes to implement two-factor authentication on a website using PHP.
Installing pragmarx/googlef2a
To set up two-factor authentication, we will be using a popular Composer package called pragmarx/google2fa. To get started, install the package using Composer: “composer require pragmarx/google2fa”. This requires you to have composer installed globally as described on www.getcomposer.org.
Updating a Database
To use 2FA, the generated 2FA token should be stored in a database. You can do this for example by adding a new column called 2fa_secret to your users table.
Creating a QR Code
It is common to add new 2FA profiles to a two-factor authentication application using QR codes. Generating these QR codes is quite simple. Whenever you want to use the Google2FA library, you have to create an instance of it:
$google2fa = new PragmaRX\Google2FA\Google2FA()
Now you can call the getQRCodeGoogleUrl() method:
$google2faUrl = $google2fa->getQRCodeGoogleUrl(‘YourApplicationName’, $userEmail, $user2faSecret)
This returns a base64 encoded image that you can show to the user using a regular <img> tag. Now the user can scan the QR code to add the profile to their 2FA application.
Generating Tokens
When a user tries to sign in, a new token should be generated. You can do so as follows:
$secretKey = $google2fa->generateSecretKey()
This returns the generated one-time token that you should save in the 2fa_secret field in your database. The code is shown to the user in the two-factor authentication application.
Verifying User Input
If the user enters a value that matches the 2fa_secret field in the database, the user can be granted access to the application. To do this, there is a method called verifyKey() available in the library:
$google2fa->verifyKey($valueInDatabase, $userInput)
If this returns true, the authentication is successful.
Laravel Integration and More Information
Integrating the Google2FA package with Laravel gives you access to Facades, which allows you to use the package without having to create a new instance every time you want to use it. To do this, as well as for more information about the package, head to the documentation at https://packagist.org/packages/pragmarx/google2fa.
No comments yet (leave a comment)