Skip to content
Connie edited this page Jan 21, 2017 · 10 revisions

Next (Display QR Code) ►

Install

npm install --save speakeasy

Two-Factor Usage

Let's say you have a user that wants to enable two-factor authentication, and you intend to do two-factor authentication using an app like Google Authenticator, Duo Security, Authy, etc. This is a three-step process:

  1. Generate a secret
  2. Show a QR code for the user to scan in
  3. Authenticate the token for the first time

Generating a key

Use Speakeasy's key generator to get a key.

var secret = speakeasy.generateSecret();
// Returns an object with secret.ascii, secret.hex, and secret.base32.
// Also returns secret.otpauth_url, which we'll use later.

This will generate a secret key of length 32, which will be the secret key for the user.

Now, we want to make sure that this secret works by validating the token that the user gets from it for the first time. In other words, we don't want to set this as the user's secret key just yet – we first want to verify their token for the first time. We need to persist the secret so that we can use it for token validation later.

So, store one of the encodings for the secret, preferably secret.base32, somewhere temporary, since we'll use that in the future to authenticate the user's first token.

// Example for storing the secret key somewhere (varies by implementation):
user.two_factor_temp_secret = secret.base32;