How to create google two factor authentication using php?
Asked Answered
S

3

13

I want to use Google 2FA in my PHP project. The user needs to enter the 6 digit 2fa code while logging in.

May you draw some tips on which direction to take?

Shaylyn answered 17/2, 2017 at 6:30 Comment(5)
What have you done so far?Cerotype
Still i didn't start this. because i don't know how do this?Shaylyn
you might want to see this answer #16908624Again
I have completed this module. Which was developed based on the below amit reference link.. But anyway thank you for your response to this.Shaylyn
If you have no clue about 2FA, you have to first learn about it and then ask. If you don't know how Google Authenticator works, same applies to their docs. Once you start some grounded work, if you come up with a problem or don't understand something, you may come and ask here.Mccormick
S
16

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
require 'vendor/autoload.php';
$authenticator = new PHPGangsta_GoogleAuthenticator();
$secret = $authenticator->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.

require 'vendor/autoload.php';
$authenticator = new PHPGangsta_GoogleAuthenticator();
$secret = $authenticator->createSecret();
echo "Secret: ".$secret."\n";  //save this at server side
 
$website = 'http://hayageek.com'; //Your Website
$title= 'Hayageek';
$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.

Two factor authentication with Google Authenticator

Step 4) Verifying OTP at server side

require 'vendor/autoload.php';
$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.
    // If somebody provides OTP at 29th sec, by the time it reaches the server OTP is expired.
    //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 {
    echo 'FAILED';
}

   source code refer this link : http://hayageek.com/two-factor-authentication-with-google-authenticator-php/
Stob answered 17/2, 2017 at 6:57 Comment(0)
R
7

Which package you use is very important because you are putting a lot of trust into the person who controls that package. I would rather not use one called PHPGangsta, and instead go with this one.

UPDATE

I leave my original answer below, but the problem with the sonata solution is that it queries api.qrserver.com. They have these docs available here. Very nice of them to offer this service but I don't know them so I can't trust them.

I have instead gone with this solution which is inspired by PHPGangsta and also seems to be an improvement. Generally, it seems like a more trustworthy solution. I use it like so:

First add it using composer:

composer require robthree/twofactorauth

Then you can print out a QR Image:

$tfa = new TwoFactorAuth(env('APP_NAME'));
$secret = $tfa->createSecret();
$qrCodeImage = $tfa->getQRCodeImageAsDataUri($user->email, $secret);
echo '<img src='.$qrCodeImage.' />';

And then validate:

$tfa = new TwoFactorAuth();
$result = $tfa->verifyCode($secret, $code);
if (empty($result)) print 'Sorry!';
else print 'Yes!';

BELOW IS MY OLD ANSWER BUT I DONT RECOMMEND USING THIS SOLUTION

Add it using composer:

composer require sonata-project/google-authenticator

Generate a new code:

$g = new \Google\Authenticator\GoogleAuthenticator();
$salt = '7WAO342QFANY6IKBF7L7SWEUU79WL3VMT920VB5NQMW';
$secret = $username.$salt;
echo '<img src="'.$g->getURL($username, 'example.com', $secret).'" />';

And then validate it:

$g = new \Google\Authenticator\GoogleAuthenticator();
$salt = '7WAO342QFANY6IKBF7L7SWEUU79WL3VMT920VB5NQMW';
$secret = $username.$salt;
$check_this_code = $_POST['code'];
if ($g->checkCode($secret, $check_this_code)) {
  echo 'Success!';
} else {
  echo 'Invalid login';
}
Robespierre answered 21/11, 2021 at 9:40 Comment(2)
I assume you just store $secret in the DB for later verifications?Spessartite
The fun part is, if you already use a different QR library (as I do) you can simply implement a new class based on this one and replace just the QR functionsSpessartite
S
0

you can use this library:

Two-Factor Authentication (2FA) Library

Install via composer:

composer require imseyed/auth2fa

TOTP Generation

The Auth2FA::TOTP method generates a Time-based One Time Password using the provided secret key and optional time slice. totp.example.php

$totp = imseyed\Auth2FA::TOTP($secret, $timeSlice);
/*
 $totp is a OPT code like: 458905
*/

If you want show expiration time of TOTP code must use Auth2FA::expire_time. that method return a number Unix timestamp.

$expirationTime = imseyed\Auth2FA::expire_time($timeSlice);
echo "Expire on ".date("H:i:s", $expirationTime)." (".($expirationTime - time())."s remind)";
/*
 $expirationTime is a unix timestamp like: 1722929683
*/

HOTP Generation

The Auth2FA::HOTP method generates an HMAC-based One Time Password using the provided secret key and counter value. hotp.example.php

$code = imseyed\Auth2FA::HOTP($secret, $counter);
/*
 $code is string like: 111222
*/

Secret Key Generation

The Auth2FA::generateSecret method generates a random secret key of the specified length.

$length = 16; // Secret key lenght
$secret = \imseyed\Auth2FA::generate_secret($length);
/*
 $secret is string like: OVZ7JFIPIXE4RTCE
*/

View resource

Sauncho answered 12/8 at 14:41 Comment(1)
You are supposed to openly state your authorship, instead of making it appear as impartial recommendation. Also an explanation why someone should choose your code over other solutions would be really useful.Koressa

© 2022 - 2024 — McMap. All rights reserved.