TOTP management
On this page
This guide covers the withTotpManagement mixin from @adonisplus/persona/totp. You will learn how to:
- Apply the mixin and understand the two-column secret pattern
- Enroll users in two-factor authentication with QR codes
- Verify TOTP codes during login
- Generate and verify recovery codes
- Customize TOTP parameters
Overview
Section titled "Overview"Two-factor authentication (2FA) adds a second verification step after the user enters their password. The user opens an authenticator app (Google Authenticator, Authy, 1Password, etc.), reads a six-digit code, and enters it into your application. The code changes every 30 seconds.
The withTotpManagement mixin implements this using the Time-based One-Time Password (TOTP) standard (RFC 6238). It encrypts secrets at rest, generates QR codes for authenticator app setup, and tracks consumed time steps to prevent replay attacks.
The mixin uses a two-column secret pattern. Your users table stores a totp_pending_secret (the secret being enrolled) and a totp_secret (the confirmed, active secret). The confirmed secret keeps working while the user sets up a new authenticator app. The pending secret is only promoted to the confirmed slot after the user proves they can generate valid codes from it.
The withTotpManagement mixin needs columns on the users table for storing secrets, timestamps, and recovery codes, and must be applied to your User model.
Install peer dependencies
Section titled "Install peer dependencies"The
withTotpManagementmixin requiresotpauthfor TOTP code generation andqrcodefor QR code rendering. Install them as production dependencies, and install@types/qrcodeas a dev dependency.npm install otpauth qrcode npm install -D @types/qrcodeAdd TOTP columns to users
Section titled "Add TOTP columns to users"Generate a migration to add five columns to your existing
userstable:totp_pending_secrettext, nullableThe encrypted secret during enrollment.totp_secrettext, nullableThe encrypted confirmed secret.totp_enabled_attimestamp, nullableWhen 2FA was activated.totp_last_consumed_timestepbigint, nullableThe last verified time step, for replay prevention.recovery_codestext, nullableA JSON array of hashed recovery codes.Both secret columns use
textbecause encrypted values are longer than the original secret. Thetotp_last_consumed_timestepcolumn usesbigIntegerto store Unix-derived time step values without overflow.node ace make:migration add_totp_columns_to_users --alter=usersimport { BaseSchema } from '@adonisjs/lucid/schema' export default class extends BaseSchema { protected tableName = 'users' async up() { this.schema.alterTable(this.tableName, (table) => { table.text('totp_pending_secret').nullable() table.text('totp_secret').nullable() table.timestamp('totp_enabled_at', { precision: 6, useTz: true }).nullable() table.bigInteger('totp_last_consumed_timestep').nullable() table.text('recovery_codes').nullable() }) } async down() { this.schema.alterTable(this.tableName, (table) => { table.dropColumn('totp_pending_secret') table.dropColumn('totp_secret') table.dropColumn('totp_enabled_at') table.dropColumn('totp_last_consumed_timestep') table.dropColumn('recovery_codes') }) } }Apply the mixin
Section titled "Apply the mixin"The
withTotpManagementmixin requires anencryptioninstance to encrypt secrets at rest and ahashinstance to hash recovery codes. You can pass either a factory function or a service manager for each.import { UserSchema } from '#database/schema' import { compose } from '@adonisjs/core/helpers' import hash from '@adonisjs/core/services/hash' import encryption from '@adonisjs/core/services/encryption' import { withTotpManagement } from '@adonisplus/persona/totp' export default class User extends compose( UserSchema, withTotpManagement(encryption, hash) ) {}You can customize the mixin by passing a config object as the third argument.
import { UserSchema } from '#database/schema' import { compose } from '@adonisjs/core/helpers' import { withTotpManagement } from '@adonisplus/persona/totp' import hash from '@adonisjs/core/services/hash' import encryption from '@adonisjs/core/services/encryption' export default class User extends compose( UserSchema, withTotpManagement(encryption, hash, { issuer: 'My App', recoveryCodesCount: 8, }) ) {}issuerstringThe issuer name displayed in the authenticator app when the user scans the QR code. Helps users identify which service the code belongs to.
Defaults to
"AdonisJS App".windownumberThe number of time steps before and after the current one that
enableTwoFactoraccepts. A window of1accepts the codes of the previous, current and next 30-second periods.verifyTotpForLoginalways uses a window of1.Defaults to
1.recoveryCodesCountnumberThe number of recovery codes to generate when calling
generateRecoveryCodes(). Each code is a single-use backup that can verify identity when the authenticator device is unavailable.Defaults to
10.
Enrollment
Section titled "Enrollment"Enrollment is a multi-step process. You generate a secret, show the user a QR code to scan with their authenticator app, and then ask them to enter a code to prove the setup worked. Only after verification does 2FA become active.
Generate the secret and show the QR code
Section titled "Generate the secret and show the QR code"import type { HttpContext } from '@adonisjs/core/http'
import { twoFactorCodeValidator } from '#validators/two_factor'
export default class TwoFactorController {
async create({ auth, inertia }: HttpContext) {
const user = auth.getUserOrFail()
// Generates and encrypts a new pending secret
await user.generateSecret()
return inertia.render('account/two_factor', {
// A base64 data URL, for an <img> tag
qrCode: await user.generateQRCode(),
// For manual entry when the user cannot scan the QR code
manualSecret: user.getEnrollmentSecret().release(),
})
}
async store({ auth, request, inertia }: HttpContext) {
const user = auth.getUserOrFail()
const { code } = await request.validateUsing(twoFactorCodeValidator)
await user.enableTwoFactor(code)
// Shown once. The plain codes cannot be read again
const recoveryCodes = await user.generateRecoveryCodes()
return inertia.render('account/recovery_codes', { recoveryCodes })
}
async destroy({ auth, response }: HttpContext) {
// Confirm the password or a TOTP code before this action
await auth.getUserOrFail().disableTwoFactor()
return response.redirect().back()
}
}
Calling generateSecret() is safe during re-enrollment. It overwrites any existing pending secret without touching the confirmed one. Login keeps working with the old authenticator app.
Verify and activate
Section titled "Verify and activate"After the user scans the QR code, ask them to enter the six-digit code from their authenticator app. The enableTwoFactor method verifies the code against the pending secret and promotes it to the confirmed slot. It throws E_INVALID_TOTP_TOKEN for a wrong code, and E_TOTP_ENROLLMENT_NOT_STARTED when there is no pending secret. Once it succeeds, user.isTwoFactorEnabled is true.
Multiple devices
Section titled "Multiple devices"When enableTwoFactor promotes the pending secret, it replaces the previous confirmed secret. Devices that use the old secret stop generating valid codes.
If a user wants to set up multiple authenticator devices, they must scan the QR code from all devices during the same enrollment session, before calling enableTwoFactor. Since all devices share the same secret, they will all generate identical codes at any given time. Verifying with a code from any one of them completes the enrollment for all.
Verifying TOTP during login
Section titled "Verifying TOTP during login"Once 2FA is enabled, verify a TOTP code as part of your login flow. The typical approach is a two-step login: first verify the password, then check isTwoFactorEnabled and prompt for a code.
// After password verification
if (user.isTwoFactorEnabled) {
// Redirect to TOTP challenge page
}When the user submits their code, verify it with verifyTotpForLogin. This method validates the code against the confirmed secret and prevents replay attacks by tracking the last consumed time step.
import User from '#models/user'
import type { HttpContext } from '@adonisjs/core/http'
import { twoFactorChallengeValidator } from '#validators/two_factor'
export default class TwoFactorChallengeController {
async store({ auth, request, response, session }: HttpContext) {
const { code, recoveryCode } = await request.validateUsing(twoFactorChallengeValidator)
// Set by the login action after the password was verified
const user = await User.findOrFail(session.get('two_factor_user_id'))
if (recoveryCode) {
await user.verifyRecoveryCode(recoveryCode)
if (user.remainingRecoveryCodesCount <= 2) {
// Ask the user to generate new recovery codes
}
} else {
await user.verifyTotpForLogin(code!)
}
session.forget('two_factor_user_id')
await auth.use('web').login(user)
return response.redirect('/dashboard')
}
}
If the code is invalid or has already been used, the method throws E_INVALID_TOTP_TOKEN.
Disabling two-factor authentication
Section titled "Disabling two-factor authentication"Call disableTwoFactor to clear all TOTP columns and recovery codes.
You should require the user to re-authenticate (password confirmation or a valid TOTP code) before allowing them to disable 2FA. Without this check, an attacker with access to an active session can silently disable 2FA.
Recovery codes
Section titled "Recovery codes"Recovery codes are single-use backup codes that let users regain access when they lose their authenticator device. Each code is a 10-character alphanumeric string in xxxxx-xxxxx format, hashed before storage.
Recovery codes are independent from the TOTP secret lifecycle. Generating recovery codes does not affect the TOTP secret, and re-enrolling does not clear existing recovery codes. However, disableTwoFactor clears both.
Generating recovery codes
Section titled "Generating recovery codes"After the user completes 2FA enrollment, generate recovery codes and display them once. The plaintext codes cannot be retrieved again.
Warning
Calling generateRecoveryCodes again replaces any existing recovery codes. The old codes will no longer work.
Verifying recovery codes
Section titled "Verifying recovery codes"When a user cannot provide a TOTP code, allow them to enter a recovery code instead. The verifyRecoveryCode method finds and consumes the matching code in a single step.
If the code is invalid, already consumed, or no recovery codes exist, the method throws E_INVALID_RECOVERY_CODE.
Check the remaining codes right after a successful verifyRecoveryCode call, since the count has just gone down. Ask the user to generate new codes when few are left.
Checking remaining codes
Section titled "Checking remaining codes"Use remainingRecoveryCodesCount to check how many recovery codes the user has left.
The challenge controller above checks this count after it consumes a recovery code.
Customization
Section titled "Customization"You can override several methods on the model to customize the TOTP behavior without changing the mixin configuration.
Custom label
Section titled "Custom label"By default, the mixin uses the user's email property as the TOTP label shown in authenticator apps. Override getTotpLabel to use a different value.
import { UserSchema } from '#database/schema'
import { compose } from '@adonisjs/core/helpers'
import { withTotpManagement } from '@adonisplus/persona/totp'
import hash from '@adonisjs/core/services/hash'
import encryption from '@adonisjs/core/services/encryption'
export default class User extends compose(UserSchema, withTotpManagement(encryption, hash)) {
getTotpLabel(): string {
return this.fullName ?? this.email
}
}
Custom TOTP instance
Section titled "Custom TOTP instance"Override createTotp to change the TOTP algorithm or the number of digits. Keep period: 30, since the replay check counts 30-second time steps. Most authenticator apps support only SHA1 and 6 digits. Change these values only for apps you know support them.
import { UserSchema } from '#database/schema'
import { compose } from '@adonisjs/core/helpers'
import { withTotpManagement } from '@adonisplus/persona/totp'
import hash from '@adonisjs/core/services/hash'
import encryption from '@adonisjs/core/services/encryption'
import { TOTP } from 'otpauth'
export default class User extends compose(
UserSchema,
withTotpManagement(encryption, hash, { issuer: 'My App' })
) {
createTotp(secret?: string): TOTP {
return new TOTP({
issuer: 'My App',
label: this.getTotpLabel(),
algorithm: 'SHA1',
digits: 6,
period: 30,
secret,
})
}
}
Custom recovery code format
Section titled "Custom recovery code format"Override seedRecoveryCode to customize the format or generation strategy.
import { randomBytes } from 'node:crypto'
import { UserSchema } from '#database/schema'
import hash from '@adonisjs/core/services/hash'
import { compose } from '@adonisjs/core/helpers'
import encryption from '@adonisjs/core/services/encryption'
import { withTotpManagement } from '@adonisplus/persona/totp'
export default class User extends compose(UserSchema, withTotpManagement(encryption, hash)) {
seedRecoveryCode(): string {
return randomBytes(8).toString('hex')
}
}
Errors
Section titled "Errors"The TOTP module throws three errors, each with status 400. See Errors for the response of each request type.
E_TOTP_ENROLLMENT_NOT_STARTEDgetSecretUri or getEnrollmentSecret) but no pending secret exists. Also thrown by verifyTotpForLogin and verifyRecoveryCode when 2FA is not enabled.E_INVALID_TOTP_TOKENE_INVALID_RECOVERY_CODEInstance properties and methods
Section titled "Instance properties and methods"totpPendingSecretstring | nullgenerateSecret(), cleared by enableTwoFactor() or disableTwoFactor().totpSecretstring | nullenableTwoFactor() when the pending secret is promoted.totpEnabledAtDate | nulltotpLastConsumedTimestepnumber | nullrecoveryCodesstring | nullgenerateRecoveryCodes(), cleared by disableTwoFactor().isTwoFactorEnabledbooleantrue when both totpSecret and totpEnabledAt are present.hasPendingTwoFactorbooleantrue when totpPendingSecret is present (enrollment in progress).remainingRecoveryCodesCountnumber0 when none have been generated.generateSecretmethodGenerates a new TOTP secret, encrypts it, and saves it to totpPendingSecret. Does not touch the confirmed secret.
await user.generateSecret()getSecretUrimethodReturns the otpauth:// URI from the pending secret. Throws E_TOTP_ENROLLMENT_NOT_STARTED if no pending secret exists.
const uri = user.getSecretUri()generateQRCodemethodReturns a QR code as a base64-encoded data URL from the pending secret. Throws E_TOTP_ENROLLMENT_NOT_STARTED if no pending secret exists.
const dataUrl = await user.generateQRCode()getEnrollmentSecretmethodReturns the decrypted pending secret wrapped in the Secret class. For manual entry when the user cannot scan the QR code. Throws E_TOTP_ENROLLMENT_NOT_STARTED if no pending secret exists.
const secret = user.getEnrollmentSecret().release()enableTwoFactormethodVerifies the code against the pending secret, promotes it to confirmed, and activates 2FA.
await user.enableTwoFactor(code)disableTwoFactormethodClears all TOTP columns and recovery codes.
await user.disableTwoFactor()verifyTotpForLoginmethodValidates a TOTP code against the confirmed secret with replay attack prevention.
await user.verifyTotpForLogin(code)getTotpLabelmethodReturns the account label for authenticator apps. Defaults to this.email. Override to customize.
user.getTotpLabel()createTotpmethodCreates a TOTP instance from the otpauth library. Override to customize algorithm, digits, or period.
const totp = user.createTotp()
const existingTotp = user.createTotp(existingSecret)seedRecoveryCodemethodGenerates a single recovery code in xxxxx-xxxxx format. Override to customize.
const generatedRecoveryCode = user.seedRecoveryCode()generateRecoveryCodesmethodGenerates recovery codes, hashes and stores them, returns the plaintext codes. Replaces any existing codes.
const codes = await user.generateRecoveryCodes()verifyRecoveryCodemethodVerifies a recovery code and consumes it on match.
await user.verifyRecoveryCode(code)