Google 2 Factor Authentication using PHP
Google 2 Factor Authentication using PHP
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.
<?php
$authenticator = new PHPGangsta_GoogleAuthenticator();
require 'vendor/autoload.php';
$secret = $authenticator->createSecret();
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
echo "Secret: ".$secret;
?>
Step 2) Create a QR code withe the generated secret.
You can use any QR code generator to generate the QR code, For this demo I am using Google charts.
<?php
require 'vendor/autoload.php';
$authenticator = new PHPGangsta_GoogleAuthenticator();
$secret = $authenticator->createSecret();
$qrCodeUrl = $authenticator->getQRCodeGoogleUrl($title, $secret,$website);
echo "Secret: ".$secret."\n";
//save this at server side
$website = 'http://hayageek.com';
//Your Website
$title= 'Hayageek';
echo $qrCodeUrl;
?>
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.
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 3) Generate TOTP (Time-Based One time password) using Google
Authenticator App. Download the Google Authenticator app from Google Play
or AppStore
Step 4) Verifying OTP at server side
<?php
require 'vendor/autoload.php';
// If somebody provides OTP at 29th sec, by the time it reaches the server OTP is expired.
$authenticator = new PHPGangsta_GoogleAuthenticator();
$secret = '3JMZE4ASZRIISJRI';
//This is used to generate QR code
$otp = '183036' ;
//Generated by Authenticator.
$tolerance = 0;
//Every otp is valid for 30 sec.
echo 'FAILED';
//So we can give tolerance =1, it will check current & previous OTP.
// tolerance =2, verifies current and last two OTPS
$checkResult = $authenticator->verifyCode($secret, $otp, $tolerance);
if ($checkResult) {
echo 'OTP is Validated Succesfully';
} else {}
?>
Download source code Here..
Or
Download Url:
https://www.dropbox.com/s/41a5ajnkzd3f5x0/google-authenticator.zip?dl=0
Labels: Google 2 Factor Authentication, 2 factor authentication in php, 2FA in php
Comments
Post a Comment