PHP - Authentication with Google Authenticator

22.02.2016

In this tutorial, I have explained how to add Two factor authentication with Google Authenticator and PHP . You can check official Google-Authentication project here. Github

Follow the steps.

Step 1) Create a unique secret code of length 16 characters.
PHPGangsta provides wrapper class for Google Authenticator. You can download using composer.

curl -sS https://getcomposer.org/installer | php
php composer.phar require phpgangsta/googleauthenticator:dev-master

Use the below code to generate the secret code.

createSecret();
echo "Secret: ".$secret;

?>

 

Step 2) Create a QR code withe the generated secret.

We need to prepare a QR code using the secret. If you want to read more about QR code generation for Google Authenticator. Github Wiki
You can use any QR code generator to generate the QR code, For this demo I am using Google charts.

createSecret();
echo "Secret: ".$secret."n"; //save this at server side

$website = 'http://webkader.com'; //Your Website
$title= 'WebKader';
$qrCodeUrl = $authenticator->getQRCodeGoogleUrl($title, $secret,$website);
echo $qrCodeUrl;

?>

 

Step 3) Generate TOTP (Time-Based One time password) using Google Authenticator App

Download the Google Authenticator app from Google Play or AppStore

Open the app and Click on '+' Button, and scan the QR code generated using Google Charts. Authenticator app generates the TOTP for your website. TOTP will change for every 30 secs.

Step 4) Verifying OTP at server side

verifyCode($secret, $otp, $tolerance); 

if ($checkResult) 
{
 echo 'OTP is Validated Succesfully';

} else {
 echo 'FAILED';
}

?>
loading