faimmedia/google-authenticator

Code to authenticate against the Google Authenticator app

1.1.0 2016-09-18 15:44 UTC

This package is auto-updated.

Last update: 2024-03-29 03:26:02 UTC


README

Introduction

2 factor authentication is pretty awesome. Far too many people use the same password for multiple things, and sometimes it's nice to actually have a secure application.

Using the Google Authenticator allows people to have another layer of security that will only allow them to access your web application/service if they have both the password and the correctly setup Google Authenticator app on their phone.

Implementation

As far as I could tell, there were (at the time of writing) 2 other PHP libraries for interacting with the Google Authenticator. Both of which work but neither of which seem to be updated much nor incorporate modern best practises.

This library has the advantage of being slightly nicer (I hope) to integrate into existing libraries, and contains inbuilt support for using a PSR-6 cache interface to reduce the possibility of a replay attack.

Usage

You can initially create the a secret code for use in your application using:

$issuer = "MyAwesomeCorp";
$accountName = "MrsSmith";
$secretFactory = new SecretFactory();
$secret = $secretFactory->create($issuer, $accountName);

This gives you a secret. You should: 1. feed this object into a QrImageGenerator so your user can scan the QR code into their phone 2. attach the secret to their user account so you can query it

The only ImageGenerator included with this library is GoogleImageGenerator which uses the Google QR code API to generate the image. If you want to use something that doesn't ever hit up an external service, it should be easy enough to extend the interface to build a base64 encoded png (or similar) that you can include as a data uri. It just needs to generate the QR code for the data in $secret->getUri();

You can verify that the user has been successful by using this:

$googleAuth = new GoogleAuthenticator();
$googleAuth->authenticate($secret, $code);

Authenticate will either boolean true/false.

If you want to use a PSR-6 cache interface to attempt to prevent replay attacks, you can do so like so:

$googleAuth = new GoogleAuthenticator();
$googleAuth->setCache($cacheItemPoolInterface);
$googleAuth->authenticate($secret, $code);

If the code has been used for that secret in the last 30 seconds, it will return false.

Examples

An example working implementation of this code can be found in the example.php file, which can be run either as:

php example.php

Which will allow you to generate a secret, then test it, or:

php example.php mysecretcode

Which will allow you to take an already existing code and again, test if your code is valid

References

Other PHP Google Authenticator implementations:

Specification for Google Authenticator: