Admin 2FA: The 2 Checks Most Tutorials Miss
A 21-page guide to adding TOTP 2FA to an admin panel properly, for Google sign-in or email and password, with replay protection, session rotation and a final checklist.
Get the PDF
Free. No email or account needed. PDF · 588 KB
The preview only loads when you tap "Read PDF here", which saves mobile data. Download gives you the original PDF file.
Key takeaways
- A TOTP code must work only once, even inside its 30-second window.
- Issue a new session ID after the second factor passes.
- Keep the encryption key out of the database that holds the secrets.
- Check admin access on every backend route, not only the page.
- Rate-limit every code check, including recovery codes.
If you followed a normal tutorial to add 2FA to your admin panel, it probably looks correct. The QR code scans, the code verifies, the dashboard opens. And two real weaknesses are likely sitting inside it. This guide explains those two checks first, then walks through the full production build for TOTP two-factor login, whether you sign in with "Continue with Google" or email and password. It works for any framework: Next.js, Firebase, Supabase, Django, Laravel or Express. The full 21-page PDF above has every diagram and the complete checklist.
Check 1: replay protection, one code for one use
A TOTP code stays valid for a whole 30-second window. If your server only asks "is this code mathematically correct right now?", the same code can be sent more than once inside that window, and it passes every time.
This happens in real life. Someone glances at your phone while you type. A code typed into a phishing page gets reused on the real site within seconds. A code leaks into a log file, a screen recording or a support chat.
The fix is small. When a code is accepted, save which time step it belonged to, per user. Reject any later attempt at that step or earlier, even if the maths is correct.
This is not optional. RFC 6238 says that once an OTP has been validated, the same OTP must not be accepted again. If you implement only one thing from this guide, make it this.
Check 2: session rotation, upgrade the session instead of flipping a flag
Almost everyone writes this:
Password verified --> session created
2FA verified --> session.twoFactorVerified = true
The session that now has admin power is the same one that existed before 2FA. Its ID was handed out at a lower privilege level. If that ID was ever captured, through session fixation, a leaked URL, a shared device or a logging mistake, the attacker's copy gets upgraded to admin the moment you pass 2FA.
The correct shape: finish the challenge, throw the challenge state away, and issue a new session. Whenever a session's privilege level changes, its identifier should change too. That is standard OWASP session guidance, and login plus MFA is exactly that kind of change.
How TOTP works
TOTP means Time-based One-Time Password. It is the standard behind Google Authenticator, Microsoft Authenticator, Authy, 1Password and the rest.
Your server and the user's app share one secret, and both know the current time. Each side splits time into 30-second steps and runs the same calculation: secret plus current time step, through HMAC-SHA1, cut down to 6 digits. Both get the same code without ever talking to each other.
You do not need any Google API or permission because a user picked Google Authenticator. The app is a generic TOTP calculator that never contacts your server.
Three rules follow from this:
- The server needs the original secret to compute future codes, so you encrypt the secret. You cannot hash it.
- Clocks drift a little, so you accept a small time window instead of one exact step.
- A code stays valid for a whole window, so you block reuse inside that window.
And use a maintained TOTP library for your language. Hand-written HMAC truncation is a classic source of silent bugs, and broken 2FA is worse than none because you will trust it.
Part 1: turning 2FA on
Only an authenticated admin can start enrollment, ideally after re-entering their password. A stolen browser session should not be enough to add a second factor.
Generate the secret on the backend. It must be cryptographically random and unique per user. Never create it in the browser, and never derive it from the user ID or email.
Encrypt it, never hash it. Passwords and recovery codes are hashed, because you only check whether they match. The TOTP secret is encrypted, because you need it back. Where the key lives decides whether encryption was worth anything. A key in the database, in the same table, hardcoded in source or committed to the repo means one database dump exposes every admin secret. Keep the key in an environment secret, a secret manager or a KMS, so a dump alone gives the attacker useless encrypted blobs.
Build the QR code locally. The otpauth:// URI contains the secret in plain text. Never send it to an online QR generator, because that hands your admin credential to a stranger's server and their logs. Generate the QR with a library in your own code, and also show the key as text for people without a camera.
Verify the first code before enabling anything. Keep the secret pending until the admin enters a correct code. If you switch 2FA on when the QR is shown and the scan silently failed, you lock yourself out.
Generate recovery codes. They must be random, single-use and hashed in storage. Rate-limit the recovery-code endpoint as strictly as the TOTP endpoint. Developers often forget it, and it becomes the weaker way into the same account.
Part 2: the login flow, both ways
With email and password, the flow becomes: verify password, check the user is an admin, check 2FA is enabled, open an MFA challenge, verify the code, rotate the session, then show the dashboard.
The MFA challenge state sits between "password correct" and "fully logged in", and it needs four properties:
| Property | Meaning |
|---|---|
| Short-lived | Expires in about 5 minutes. It is not a session. |
| Single-use | Destroyed when the challenge succeeds or is abandoned. |
| Bound | Tied to that one login attempt and that one user. |
| Powerless | Every normal and admin API rejects it. It can call one endpoint: verify. |
Miss the last one and you have built a half-privileged session that skips 2FA entirely.
With "Continue with Google", Google decides who the user is, not who gets your admin panel. Validate the Google ID token on the server: the signature, aud (your client ID), iss (Google) and exp. Key the account on Google's sub claim, not the email, because emails can change. If your platform (Firebase with Identity Platform, Supabase, Auth0) already supports TOTP MFA, use its official flow.
When verifying the code, accept a small drift window (one step either side, about 90 seconds in total) and keep the server NTP-synced. Reject replays per user. Compare codes in constant time, including your own recovery-code check.
Then rotate the session: invalidate the challenge, issue a new session ID, and record mfa = verified and the time on the server. A frontend flag like twoFactorVerified = true is decoration, because anyone can set it.
Part 3: hardening everything around the login
Protect the backend, not just the page. This is the most important section and the most skipped. A 2FA screen in front of /admin does not protect /api/admin/users or DELETE /api/admin/user/123. If those endpoints only check "is there a session?", anyone with a pre-MFA session can call them directly. Every sensitive endpoint must check three things itself: a valid session (else 401), the admin role (else 403), and MFA completed on this session (else 403).
Rate limit every verification endpoint: TOTP, recovery codes and the enrollment step. A 6-digit code has a million combinations, and unlimited guessing makes 2FA cosmetic. Treat a burst of wrong codes on an admin account as an alert.
Protect "Disable 2FA". Turning 2FA off, replacing a factor and generating new recovery codes all need re-authentication with the password and a current code. An existing session alone is never enough.
Never log secrets or codes. Check what your error tracker, request capture, analytics and crash reporter collect. A full request body with the secret in an error report is the leak nobody notices for a year.
Sessions and cookies: HTTPS everywhere, cookies with Secure, HttpOnly and SameSite, CSRF protection for cookie auth, session IDs rotated on every privilege change, and no auth material in localStorage. For destructive actions like deleting users, changing roles or payment settings, ask for a fresh code if the last check was more than a few minutes ago.
Keep an audit trail of 2FA enabled and disabled, recovery codes used, repeated failures and every successful admin login with time and IP, without the secrets themselves.
One honest limitation
TOTP is a big improvement over passwords alone, but it is not phishing-proof. A convincing fake login page can capture a code and use it immediately. Replay protection stops reuse, not that first real-time relay. For high-value admin systems, look at passkeys, WebAuthn and hardware security keys, which resist phishing by design. OWASP recommends that direction for privileged accounts.
This guide gives you the architecture and the rules, not a snippet to paste, because the real code depends on your stack. Take the checklist in the PDF to whichever stack you use and make every box tick. If you cannot tick a box, that box is a bug.