Skip to content

Modules: 2FA

Alex Bruno Cáceres edited this page Jun 25, 2024 · 2 revisions

Methods to implement Two-Factor Authentication (2FA) in web applications with the One-Time Password (OTP) approach, compatible with any secure and reliable authenticator app.

Warning: Avoid using these methods on the front-end side of a web application, this may cause security issues. Use them inside your Node.js back-end API, where you can store and process data securely.

generateSecretKey

Generates a user secret key for a two-factor authentication (2FA) system.

Returns the secret key along with a QR code image for authenticator app activation.

import { generateSecretKey } from '@jsweb/utils/modules/2fa'

// Sample: You must identify your app name
// to be properly listed on the user's authenticator app
const app = 'My secure app'

// Sample: You must identify the username who will register the secret key,
// this will be listed as a reference in the user's authenticator app
const user = 'username'

const { qrcode, secret } = generateSecretKey(app, user)

console.log('secret', secret) // NB2W45DFOIZA

console.log('qrcode', qrcode) // data:image/svg+xml;base64,...
  • The generated secret key must be securely stored along with the user authentication data. It will be used further to check validity of OTP codes.
  • The QR code image is encoded as base64 string format for browsers and can be easily rendered with an HTML image tag. The user can scan the image with any authenticator app to activate 2FA.

checkUserOTP

Checks if the user-entered OTP is valid for the given secret key.

import { checkUserOTP } from '@jsweb/utils/modules/2fa'

// Sample: Get the secret from user auth data,
// previously generated and stored
const secret = 'NB2W45DFOIZA'

// Sample: Get the user-entered OTP,
// submitted in a security step on your app login
const otp = '234789'

const valid = checkUserOTP(secret, otp) // Boolean (true/false)
  • Use the validity check method to securely verify the user authentication.
  • OTP codes for a secret key created with generateSecretKey are valid just for 30 seconds.

Clone this wiki locally