Two-Factor Authentication with Node.js

By  on  
Google Authenticator

There are a variety of strategies for protecting your important online credentials.  We often hear about password managers and generators, but for me, the more important strategy is using two-factor authentication (2FA).  Passwords can be guessed, phone numbers can be spoofed, but using two-factor authentication essentially requires that user be in possession of a physical device with an app like Google Authenticator, loaded with a secret key for the given app, which provides an extra layer of security.

I didn't use to take two-factor authentication seriously, until someone stole my domain name and tried to launder it to a safe haven for thieved domains.  While I don't know how exactly they did it, I'm fairly certain they got access to my email address, created filters so I wouldn't see the emails, etc.  Had I used two-factor authentication, neither my email or GoDaddy accounts could have been accessed.  Or you could take it from Cody Brown who had $8,000 in cryptocurrency stolen in minutes because the vendor used phone number validation to allow transactions to be approved.  Today I use two-factor authentication for all of my important email, work, and financial accounts.

Since I use 2FA so often, I wanted to see how the process is managed by a developer for its users.  That would include generating the secret key, creating its QR code representation, scanning the code into Google Authenticator (done by the user), and then validating that GA-given code against the user's key.  I found an easy to use Node.js library, speakeasy, to do so!

Setup Step 1:  Generate a Secret Key

Assuming you've installed speakeasy via npm install speakeasy, the two-factor authentication setup is kicked off by generating a unique secret key for the user:

var speakeasy = require('speakeasy');

var secret = speakeasy.generateSecret({length: 20});
console.log(secret.base32); // Save this value to your DB for the user

// Example:  JFBVG4R7ORKHEZCFHZFW26L5F55SSP2Y

This secret key should be stored with the user's record in your database, as it will be used as a reference to validate 2FA codes in the future.

Setup Step 2:  Generate a QR Image

Apps like Google Authenticator allow users to scan a QR code or enter the text key.  Scanning an image is much faster so offering the QR code will be of great convenience to your user:

var QRCode = require('qrcode');

QRCode.toDataURL(secret.otpauth_url, function(err, image_data) {
  console.log(image_data); // A data URI for the QR code image
});

QRCode.toDataURL provides an image data URI that you can use for the img src attribute.  If you aren't familiar with a QR code, it will look something like this:

QR Code

User Step 1:  Scan the QR Code / Add Site to Authenticator

At this point the user should have opened Google Authenticator (or Authy, etc.) and scanned the QR code; an entry for your web app will be added within the device's app.  From this point forward, whenever the user wants to log in (or perform any action you'd like to be protected), your system should recognize the user wants to use 2FA and you should require they enter the token from their app.

Google Authenticator

For the purposes of debugging, you can get what should be the user code value at a given time via:

// Load the secret.base32 from their user record in database
var secret = ...

var token = speakeasy.totp({
  secret: secret,
  encoding: 'base32'
});

User Step 2: Providing the Token / Validating the Token

When your web app prompts the user for the current 2FA token, and the user provides a 6 digit token, the web app must validate that token:

// This is provided the by the user via form POST
var userToken = params.get('token');

// Load the secret.base32 from their user record in database
var secret = ...

// Verify that the user token matches what it should at this moment
var verified = speakeasy.totp.verify({
  secret: secret,
  encoding: 'base32',
  token: userToken
});

If the token matches, the user can be trusted; if the token does not match, the web app should prompt the user to try again.  Remember that Authenticator provides a new token every {x} seconds so an incorrect token shouldn't immediately raise a red flag; the token may have simply expired by the time the user submitted the form.

Live Demo

The speakeasy developers have created a live speakeasy 2FA demo for you to play with so that you can understand the steps involved from both a user and a developer perspective.

This post is only meant to be a brief, high level overview of implementing two-factor authentication -- please read the speakeasy documentation to get a more detailed explanation as well as learn about more specific 2FA options.  In an ideal world, two-factor authentication would be enabled by default for most logins, however it can be confusing for the majority of web users (think of the very non-technical user), so I can understand why 2FA is considered an extra security measure for now.  A big thanks to speakeasy's developers for their easy to use Node.js library, awesome documentation, and simple demo!

Recent Features

  • By
    Camera and Video Control with HTML5

    Client-side APIs on mobile and desktop devices are quickly providing the same APIs.  Of course our mobile devices got access to some of these APIs first, but those APIs are slowly making their way to the desktop.  One of those APIs is the getUserMedia API...

  • By
    Being a Dev Dad

    I get asked loads of questions every day but I'm always surprised that they're rarely questions about code or even tech -- many of the questions I get are more about non-dev stuff like what my office is like, what software I use, and oftentimes...

Incredible Demos

Discussion

  1. Another easy way to implement 2-Factor Authentication is to hand off the authentication work to something like AWS Cognito. Not only can it handle 2FA, but it can take care of all your authentication needs, freeing you up to focus on other things.

  2. Oleks

    Thanks for the nice article! I created some simple docker service for my project based on this info for my projects, somebody could find useful (no qr code scanning though): https://github.com/oleksm/2fa

  3. David

    Hi! Is there a good guide you’d recommend for generating backup codes? They don’t seem to be part of the TOTP spec from what I understand.

  4. Hi David, great post!

    Quick question: how do you recommend storing the base32 secret generated by speakeasy for each user? As you know storing passwords in plain text is bad practice, and this is kind of similar.

    Is there any way to encypt/hash the secret in a way that hides the original key, but still allows verification of a one-time token?

  5. Malkeet SIngh

    Hi David, Amazing job at explaining how 2FA works with node.js.

    Just a quick question, how do I set a custom name property for my app in the google authenticator? For example currently, it shows ‘Secret Key’ as the name for every app. I want to set it to a custom name like ‘ My App’. I know I can do it manually in GA but I want to set it automatically.

    Thanx in advance.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!