Skip to content
Connie edited this page Jan 20, 2017 · 5 revisions

◄ Back (Display QR Code)     Next (General Usage for Time-Based Token) ►

Verifying the token

Finally, we want to make sure that the token on the server side and the token on the client side match. The best practice is to do a token check before fully enabling two-factor authentication for the user. This code applies to the first and subsequent token checks.

After the user scans the QR code, ask the user to enter in the token that they see in their app. Then, verify it against the secret.

// Let's say the user says that the token they have is 132890
var userToken = '132890';

// Let's say we stored the user's temporary secret in a user object like above:
// (This is specific to your implementation)
var base32secret = user.two_factor_temp_secret;
// Use verify() to check the token against the secret
var verified = speakeasy.totp.verify({ secret: base32secret,
                                       encoding: 'base32',
                                       token: userToken });

verified will be true if the token is successfully verified, false if not.

If successfully verified, you can now save the secret to the user's account and use the same process above whenever you need to use two-factor to authenticate the user, like during login.

// Example for saving user's token (varies by implementation):
user.two_factor_secret = user.two_factor_temp_secret;
user.two_factor_enabled = true

Now you're done implementing two-factor authentication!