Minimal TOTP enrollment and verification with nestjs-xotp.
This example shows two patterns from the underlying xotp library:
- Enrollment —
XOTPTOTPService.create()generates a per-user secret andotpauth://URI. - Verification — a shared injected
XOTPTOTPServicevalidates tokens with each user's stored secret.
Secrets are kept in memory only. In production, persist and encrypt them in your database.
TwoFactorModuleimportsXOTPModule.forRoot()soXOTPTOTPServicecan be injected intoTwoFactorService.- Enrollment uses
XOTPTOTPService.create()to generate a per-user secret andotpauth://URI. - Verification uses the shared injected
XOTPTOTPServicewith each user's stored secret.
From the repository root:
npm run build
cd examples/2fa-basic
npm install
npm run startFor local development without a separate build step:
npm run start:devThe app listens on http://localhost:3000.
Enroll an account:
curl -s -X POST http://localhost:3000/2fa/enroll \
-H 'content-type: application/json' \
-d '{"account":"user@example.com"}'Response:
{
"account": "user@example.com",
"secret": "JBSWY3DPEHPK3PXP",
"keyUri": "otpauth://totp/MyApp:user@example.com?secret=...&issuer=MyApp"
}Add the keyUri to an authenticator app (or generate a QR code from it). Then verify a code:
curl -s -X POST http://localhost:3000/2fa/verify \
-H 'content-type: application/json' \
-d '{"account":"user@example.com","token":"123456"}'Response:
{ "valid": true }Fetch the key URI again for an enrolled account:
curl -s http://localhost:3000/2fa/key-uri/user@example.com| Method | Path | Description |
|---|---|---|
POST |
/2fa/enroll |
Generate secret and key URI for an account |
POST |
/2fa/verify |
Validate a TOTP token |
GET |
/2fa/key-uri/:account |
Return the key URI for an enrolled account |