Google2FA is a PHP implementation of the Google Two-Factor Authentication Module, supporting the HMAC-Based One-time Password (HOTP) algorithm specified in RFC 4226 and the Time-based One-time Password (TOTP) algorithm specified in RFC 6238.
This package is agnostic, but also supports the Laravel Framework.
- PHP 5.3.7+
You don't need Laravel to use it, but it's compatible with
- Laravel 4.1+
- Laravel 5+
Use Composer to install it:
composer require pragmarx/google2fa
Add the Service Provider and Facade alias to your app/config/app.php
(Laravel 4.x) or config/app.php
(Laravel 5.x):
'PragmaRX\Google2FA\Vendor\Laravel\ServiceProvider',
'Google2FA' => 'PragmaRX\Google2FA\Vendor\Laravel\Facade',
use PragmaRX\Google2FA\Google2FA;
$google2fa = new Google2FA();
return $google2fa->generateSecretKey();
$google2fa = app()->make('PragmaRX\Google2FA\Contracts\Google2FA');
return $google2fa->generateSecretKey();
use PragmaRX\Google2FA\Contracts\Google2FA;
class WelcomeController extends Controller {
public function generateKey(Google2FA $google2fa)
{
return $google2fa->generateSecretKey();
}
}
return Google2FA::generateSecretKey();
Generate a secret key for your user and save it:
$user = User::find(1);
$user->google2fa_secret = Google2FA::generateSecretKey();
$user->save();
Show the QR code to your user:
$google2fa_url = Google2FA::getQRCodeGoogleUrl(
'YourCompany',
$user->email,
$user->google2fa_secret
);
{{ HTML::image($google2fa_url) }}
And they should see and scan the QR code to their applications:
And to verify, you just have to:
$secret = Input::get('secret');
$valid = Google2FA::verifyKey($user->google2fa_secret, $secret);
It's really important that you keep your server time in sync with some NTP server, on Ubuntu you can add this to the crontab:
ntpdate ntp.ubuntu.com
Although the probability of collision of a 16 bytes (128 bits) random string is very low, you can harden it by:
$secretKey = $google2fa->generateSecretKey(32); // defaults to 16 bytes
$secretKey = $google2fa->generateSecretKey(16, $userId);
You can scan the QR code on this page with a Google Authenticator app and view the code changing (almost) in real time.
To use the two factor authentication, your user will have to install a Google Authenticator compatible app, those are some of the currently available:
- Authy for iOS, Android, Chrome, OS X
- FreeOTP for iOS, Android and Peeble
- FreeOTP for iOS, Android and Peeble
- Google Authenticator for iOS
- Google Authenticator for Android
- Google Authenticator for Blackberry
- Google Authenticator (port) on Windows app store
The package tests were written with phpspec.
Google2FA is licensed under the BSD 3-Clause License - see the LICENSE
file for details
Pull requests and issues are more than welcome.