Add 2FA/MFA to authentication flow
✓Works with OpenClaudeYou are a security engineer implementing two-factor authentication. The user wants to add 2FA/MFA to an existing authentication flow using TOTP (Time-based One-Time Password) and backup codes.
What to check first
- Verify you have a
speakeasyorotplibpackage installed:npm list speakeasyornpm list otplib - Confirm your database schema includes columns for
twoFactorSecret,twoFactorEnabled, andbackupCodeson the user model - Check that your JWT secret or session store is configured before adding 2FA middleware
Steps
- Install the required packages:
npm install speakeasy qrcodefor TOTP secret generation and QR code creation - Create a 2FA setup endpoint that generates a new secret using
speakeasy.generateSecret()and returns a QR code viaqrcode.toDataURL() - Create a 2FA verification endpoint that accepts the user's TOTP token and validates it with
speakeasy.totp.verify() - Generate backup codes (8-10 alphanumeric strings) when 2FA is first enabled and store them hashed in the database
- Add a 2FA check middleware in your protected routes that intercepts unauthenticated TOTP attempts
- Create a backup code redemption endpoint that validates and invalidates used codes
- Implement a "remember this device" feature by storing a device fingerprint in a cookie with a 30-day expiration
- Add a disable 2FA endpoint that requires password re-authentication plus a valid TOTP token
Code
const speakeasy = require('speakeasy');
const QRCode = require('qrcode');
const crypto = require('crypto');
// Step 1: Generate 2FA secret and QR code
async function setupTwoFactor(userId, userEmail) {
const secret = speakeasy.generateSecret({
name: `YourApp (${userEmail})`,
issuer: 'YourApp',
length: 32
});
const qrCode = await QRCode.toDataURL(secret.otpauth_url);
return {
secret: secret.base32,
qrCode: qrCode,
backupCodes: generateBackupCodes(8)
};
}
// Step 2: Generate and hash backup codes
function generateBackupCodes(count) {
const codes = [];
for (let i = 0; i < count; i++) {
codes.push(crypto.randomBytes(4).toString('hex').toUpperCase());
}
return codes;
}
function hashBackupCode(code) {
return crypto.createHash('sha256').update(code).digest('hex');
}
// Step 3: Verify TOTP token
function verifyTOTP(secret, token) {
return speakeasy.totp.verify
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Authentication Skills
Other Claude Code skills in the same category — free to download.
JWT Auth
Implement JWT authentication from scratch
OAuth Setup
Set up OAuth 2.0 with multiple providers
NextAuth Setup
Configure NextAuth.js/Auth.js
Passport Setup
Set up Passport.js with strategies
Magic Link Auth
Implement passwordless magic link auth
Session Management
Implement secure session management
API Key Auth
Create API key authentication system
SSO Setup
Set up Single Sign-On (SAML/OIDC)
Want a Authentication skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.