1. Introduction
2-Step Verification is a feature to help users protec their account when doing important activities such as login, making payment or confirmation, the two steps are:
- Step 1: inputting password.
- Step 2: inputting a verification code which has a limited lifetime (30s to minutes), this code is called OTP code. OTP code is sent to user via email, SMS or mobile application.
Normally, OTP is sent via SMS, some services make a call instead of sending SMS to increase security. The both methods will cost your service large money. Another method is using mobile application to generate OTP code, OTP code is based on real time then that mobile application does not need internet connection to generate the code.
Service providers (for ex.: banks) usually have their own OTP mobile applications. However, you can use Google Authenticator which is a total free application and provided by Google to generate OTP code for your own service. Most of Google Authenticator sources on github require Laravel, it is very convenient if you are developing your web project from beginning. In contrast to this, you will have to spend much time to integrate this environment to your existing web, in some case, you will have to install exact Laravel version. Moreover, it will increase the number of files in of your web project.
Therefore, I modified one of them to make it become a plug-and-play PHP library, you can call it directly without installing Laravel.
2. Download and usage
a. Download
You can use git command to download
git clone https://github.com/bigdolphin/google2fa-without-laravel
Or download directly from github: https://github.com/bigdolphin/google2fa-without-laravel
b. Test
php test.php
Install Google Authenticator: https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&hl=vi&gl=US
Open this app and scan the QR or input the secret key above into the app.
The app will generate an OTP code which will change after 30s. Type the code into the web to validate.
c. Usage
– Call library
<?php
require_once("PragmaRX/Google2FA/Google2FA.php");
use PragmaRX\Google2FA\Google2FA;
?>
– Create instance
<?php
$g = new Google2FA();
?>
– Generate secret key
<?php
$secret = $g->generateSecretKey();
?>
– Generate QR image link
<?php
$url = $g->getQRCodeUrl("Company name","email",$secret);
$url = "http://www.google.com/chart?chs=150x150&chld=M|0&cht=qr&chl=".$url;
?>
– Validate OTP code with secret key
<?php
$valid = $g->verifyKey($secret, $code);
?>
$valid will 1 if $code is correct.
Comments
One response to “PHP Library for two-step verification with Google Authenticator App”
I am really pleased to read this web site posts which includes lots of valuable information, thanks for providing such information.