$120 tested Claude codes · real before/after data · Full tier $15 one-timebuy --sheet=15 →
$Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. download --free →
clskills.sh — terminal v2.4 — 2,347 skills indexed● online
[CL]Skills_
Authenticationadvanced

Two Factor Auth

Share

Add 2FA/MFA to authentication flow

Works with OpenClaude

You 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 speakeasy or otplib package installed: npm list speakeasy or npm list otplib
  • Confirm your database schema includes columns for twoFactorSecret, twoFactorEnabled, and backupCodes on the user model
  • Check that your JWT secret or session store is configured before adding 2FA middleware

Steps

  1. Install the required packages: npm install speakeasy qrcode for TOTP secret generation and QR code creation
  2. Create a 2FA setup endpoint that generates a new secret using speakeasy.generateSecret() and returns a QR code via qrcode.toDataURL()
  3. Create a 2FA verification endpoint that accepts the user's TOTP token and validates it with speakeasy.totp.verify()
  4. Generate backup codes (8-10 alphanumeric strings) when 2FA is first enabled and store them hashed in the database
  5. Add a 2FA check middleware in your protected routes that intercepts unauthenticated TOTP attempts
  6. Create a backup code redemption endpoint that validates and invalidates used codes
  7. Implement a "remember this device" feature by storing a device fingerprint in a cookie with a 30-day expiration
  8. 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

Quick Info

Difficultyadvanced
Version1.0.0
AuthorClaude Skills Hub
auth2famfa

Install command:

curl -o ~/.claude/skills/two-factor-auth.md https://claude-skills-hub.vercel.app/skills/auth/two-factor-auth.md

Related Authentication Skills

Other Claude Code skills in the same category — free to download.

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.