Easy Two Factor Authentication (2FA) with Google Authenticator & PHP

I recently implemented two factor authentication to secure administrator logins to something important.

Doing so was much easier than I thought thanks to Google Authenticator and an open source composer package, so I thought I’d share this quick article to help others who might not have done it yet.

What is Two Factor Authentication?

Two Factor Authentication, also known as 2FA, two step verification or TFA (as an acronym), is an extra layer of security that is known as “multi factor authentication” that requires not only a password and username but also something that only, and only, that user has on them, i.e. a piece of information only they should know or have immediately to hand — such as a physical token.

So how does the user get the code?

  • Historically this required the user to carry a widget or card reader device (in the case of bank accounts) on their person, to generate a unique code.
  • Recently a popular method has been sending the user an SMS with a one time use code.

However there are other options…

How Google Authenticator works

  1. When enabling 2FA, the application you’re securing generates a QR code that user’s scan with their phone camera to add the profile to their Google Authenticator app.
  2. Your user’s smart phone then generates a new code every 30 seconds to use for the second part of authentication to the application.
Image for post
Image for post

Implementing Google Authenticator on your website using PHP

You’ll use the library to:

  • Generate the QR code for your user’s to scan when they enable 2FA.
  • Verify that the code entered is valid at login.

Generating the QR Code

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

Tips:

Verifying entered codes

You need to use the same secret you used to generate the barcode in order to validate the user’s input.

$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';
}

While Google Authenticator might not be the most desirable 2FA method for your customers, there’s no reason you can’t implement it for staff or administrators when it’s this easy.

Written by

I’m a logistics technology, e-commerce, cross-border shipping & fulfilment expert. CTO at The Parcel Monkey Group, a globally operating logistics tech company.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store