n8n Two-Factor Authentication Failed: Why Login Is Rejected

Step by Step Guide to solve n8n Two-Factor Authentication Failed

 


 

Who this is for: n8n administrators and power‑users who have enabled TOTP‑based 2FA and are encountering “invalid code” errors during login. We cover this in detail in the n8n Authentication Errors Guide.

Quick Diagnosis
If n8n rejects your login after you enter a 2FA code, try these three steps in order:

# Action Expected Result
1 Verify the code is from the current 30‑second window. Correct code accepted.
2 Sync the device clock with an NTP server (e.g., time.google.com). Time drift eliminated, code matches.
3 Regenerate a fresh Backup Code from User Settings → Two‑Factor Auth and use it once. Bypasses the broken authenticator, restores access.

If all three fail, follow the detailed troubleshooting guide below.


1. Understanding n8n’s 2FA Flow

If you encounter any password policy violation resolve them before continuing with the setup.

Micro‑summary: n8n validates TOTP codes using the otplib library; mismatches usually stem from clock drift or secret issues.

n8n stores a base‑32 secret (hashed in the DB) when you enable 2FA. During login it:

  1. Generates a 6‑digit code from the secret and the current Unix time (30‑second step).
  2. Accepts the submitted code if it matches the generated value within a ±1 step tolerance.

Because the algorithm is deterministic, any mismatch is almost always caused by time drift, secret corruption, or incorrect entry.

Key terms: TOTP, RFC 6238, otplib, base‑32 secret, NTP sync, backup codes, QR code, authenticator app, rate‑limit, brute‑force protection.


2. Quick Diagnostic Checklist

If you encounter any user not found error resolve them before continuing with the setup.

Micro‑summary: Verify the most common failure points before diving deeper.

Steps Check How to Verify
1 Authenticator app points to the correct n8n entry Open the app and confirm the label matches the QR code shown in User Settings → Two‑Factor Auth.
2 Device clock is accurate Run date -u (Linux/macOS) or view **Internet Time** settings (Windows).
3 Code entered within the 30‑second window Watch the countdown timer in the app; avoid copying after it expires.
4 No duplicate 2FA entries in the DB Query the user’s secret (see § 3.3).
5 Rate‑limit not triggered Look for a “Too many attempts” message; wait 5 min before retrying.

Resolve any failing check before proceeding.


3. Step‑by‑Step Troubleshooting

3.1. Verify Time Synchronization

Why it matters: TOTP requires synchronized clocks; a drift of even a minute breaks every code.

Linux/macOS

# Install an NTP client (if missing)
sudo apt-get install ntpdate   # Debian/Ubuntu
# or
brew install ntp               # macOS

# Synchronize the clock immediately
sudo ntpdate -u time.google.com

Windows

  1. Open Settings → Time & Language → Date & time.
  2. Enable Set time automatically and Set time zone automatically.
  3. Click Sync now.

EEFA Note: In production containers, avoid installing ntpdate at runtime. Keep the host OS synced via NTP or use a side‑car container that maintains clock accuracy.


3.2. Regenerate the TOTP Secret

If the stored secret is corrupted, the generated code will never match.

  1. Log in with a backup code (see § 3.4).
  2. Go to User Settings → Two‑Factor Auth → Reset.
  3. Scan the new QR code with your authenticator app.
  4. Save the newly generated backup codes.

Reset via API (automation)

curl -X POST https://your-n8n-instance.com/rest/v1/user/me/2fa/reset \
  -H "Authorization: Bearer <admin-token>" \
  -H "Content-Type: application/json"
{
  "otpauth_url": "otpauth://totp/n8n:user@example.com?secret=JBSWY3DPEHPK3PXP&issuer=n8n",
  "backup_codes": ["ABCD‑EFGH‑IJKL‑MNOP", "..."]
}

EEFA Warning: Protect this endpoint with strong admin authentication and audit every reset event.


3.3. Check for Duplicate 2FA Records

Multiple secret rows for the same user can cause the validation routine to compare against the wrong one.

List existing 2FA records

SELECT id, secret, created_at
FROM "user_2fa"
WHERE user_id = $1;

Remove stale entries (keep the newest)

DELETE FROM "user_2fa"
WHERE user_id = $1
  AND id <> (
    SELECT id
    FROM "user_2fa"
    ORDER BY created_at DESC
    LIMIT 1
  );

EEFA Tip: Add a unique index on (user_id) to prevent future duplicates.


3.4. Use a Backup Code to Regain Access

When all else fails, n8n’s one‑time backup codes provide a fallback.

  1. Open the Backup Codes list in User Settings.
  2. Copy any unused code and paste it into the 2FA field.
  3. Immediately generate a new set of backup codes (the used ones become invalid).

EEFA Best Practice: Store backup codes in a password manager, never in plain‑text files.


4. Common Pitfalls & How to Avoid Them

Pitfall Symptom Fix
Authenticator app switched to a different account Code always rejected despite correct time. Re‑scan the QR code for the correct n8n account.
Device clock set to a different timezone Code works on one device, fails on another. Use UTC or enable automatic time sync.
Browser autofill inserts a stale code “Invalid code” even after generating a new one. Clear the field manually; disable autofill for the 2FA input.
Rate‑limit lockout after many attempts “Too many attempts, try again later.” Wait the lockout period (default 5 min) or raise maxAttempts in config/security.json for trusted environments.
Database migration truncated the secret All users experience 2FA failure after an upgrade. Verify the secret column type (VARCHAR(128)) and re‑run the migration script.

5. Production‑Ready Configuration Recommendations

Setting Recommended Value Reason
TOTP_STEP 30 seconds Aligns with RFC 6238 defaults; compatible with all major apps.
TOTP_WINDOW 1 (±1 step) Balances usability and security.
MAX_2FA_ATTEMPTS 5 per 10 min Thwarts brute‑force while limiting lockouts.
BACKUP_CODE_COUNT 10 Provides enough one‑off access without encouraging reuse.
NTP_SYNC_INTERVAL 1h (host level) Keeps server clock accurate for API‑driven verification.

Add these to ~/.n8n/config.json or as environment variables:

TOTP_STEP=30
TOTP_WINDOW=1
MAX_2FA_ATTEMPTS=5
BACKUP_CODE_COUNT=10

EEFA Note: Never log the raw TOTP secret. Mask it (******) if debugging is required.


6. When to Escalate

Condition Action
Multiple users report the same failure after a deployment Roll back the last code change; inspect migration scripts for secret truncation.
Logs show ERR_TOTP_MISMATCH for every attempt despite correct codes Verify server time (date -u) and NTP sync; involve the hosting provider if drift persists.
Backup codes also fail Examine the backup_codes column for JSON corruption; restore from a recent DB backup.

8. Next Steps

  • Secure 2FA rollout – best practices for onboarding teams.
  • Audit logging for authentication events – how to retain tamper‑proof logs in n8n.
  • Custom 2FA providers – integrating Duo or Auth0 with n8n’s webhook authentication.

Conclusion

n8n’s TOTP‑based 2FA is reliable when the clock, secret, and entry are in sync. Most login rejections stem from clock drift, corrupted secrets, or stale backup codes. By confirming time synchronization, resetting the secret, cleaning duplicate DB records, and leveraging backup codes, you can restore access quickly and keep the system secure. Apply the production‑grade configuration recommendations to minimize future failures and maintain audit‑ready logs.

Leave a Comment

Your email address will not be published. Required fields are marked *