kelunik / two-factor
Two factor authentication.
Installs: 1 810
Dependents: 3
Suggesters: 0
Security: 0
Stars: 36
Watchers: 3
Forks: 4
Open Issues: 0
Requires
- php: >=7.1
- paragonie/constant_time_encoding: ^1|^2
Requires (Dev)
- amphp/php-cs-fixer-config: dev-master
- phpunit/phpunit: ^7 | ^8 | ^9
README
kelunik/two-factor
is a Google Authenticator compatible OATH implementation.
Requirements
- PHP 5.5+
Installation
composer require kelunik/two-factor
Demo
There's a runnable demo contained in this repository.
Usage
Generate a secret per user
$oath = new Oath; // this generates a key in binary format $key = $oath->generateKey(); // store key for user
Let user setup two factor device
$oath = new Oath; $key = "..."; // load user key from storage // Use the URI to provide an easy to scan QR code $uri = $oath->getUri($key); // Alternatively display the key for manual input $secret = $oath->encodeKey($key);
You can use your favourite JavaScript or PHP library to generate the QR code. For a working example, we're using qr.js
.
<form action="/2fa/setup" method="POST"> Scan the following QR code and click continue once you're ready. <input type="hidden" value="{{$uri}}" id="2fa-uri"> <canvas id="qr-code"></canvas> <script src="/js/qr.min.js"></script> <script> qr.canvas({ canvas: document.getElementById("qr-code"), value: document.getElementById("2fa-uri").value }); </script> <button type="submit">Continue</button> </form>
Validate TOTP value
$oath = new Oath; $key = "..."; // load user key from storage $isValid = $oath->verifyTotp($key, $totpValue); // If the token is valid, ensure that it can't be used again. // Because we use the default grace window size of two, // we have to store the used TOTP value for at least 90 seconds, // to prevent its usage explicitly.