TL;DR: Adding MFA to homegrown authentication improves sign-in assurance, but the operational risk shifts to factor enrollment, challenge expiry, retry handling, and secret storage, according to WorkOS. The control question is no longer whether MFA exists, but whether the surrounding identity workflow prevents reuse, exposure, and weak fallback paths.
At a glance
What this is: This is a practical guide to adding MFA into a custom authentication flow, with guidance on TOTP and SMS, challenge handling, and safe factor storage.
Why it matters: It matters because MFA controls fail when enrollment, challenge lifetime, logging, and secret handling are weak, and those same design flaws affect human login flows, service account workflows, and broader identity governance.
By the numbers:
- Only 20% have formal processes for offboarding and revoking API keys, and even fewer have procedures for rotating them.
- 71% of NHIs are not rotated within recommended time frames, increasing the risk of compromise over time.
- 96% of organisations store secrets outside of secrets managers in vulnerable locations including code, config files, and CI/CD tools.
- 80% of identity breaches involved compromised non-human identities such as service accounts and API keys.
👉 Read WorkOS's guide to adding MFA to a homegrown authentication system
Context
MFA is the extra verification step that sits beside passwords, but in a homegrown auth system its security depends on more than the challenge itself. The real risk is the surrounding identity workflow: how factors are enrolled, how long challenges remain valid, how reuse is blocked, and whether secrets are stored safely from the start.
For IAM teams, the lesson is the same across human, NHI, and autonomous identity programmes. Once authentication is implemented inside application code, governance has to cover lifecycle controls, logging, retry behaviour, and the trust boundary around secrets, not just the user prompt.
WorkOS provides the source example for implementing those flows, but the practitioner problem is broader than one integration. A safe MFA design is a governance pattern, not a UI feature.
Key questions
Q: How should security teams implement MFA in a homegrown authentication flow?
A: Start by making factor enrollment, challenge issuance, verification, and recovery server-side identity states, not ad hoc application logic. Prefer TOTP for primary assurance, enforce short-lived one-time challenges, and record every enrollment and verification event so the control can be governed and audited.
Q: Why do SMS-based MFA flows create more risk than TOTP in custom auth systems?
A: SMS depends on a transport channel that can be intercepted through SIM swap, phishing, or malware, so it is weaker as a primary factor. TOTP reduces exposure by keeping the second factor tied to a shared secret and a local authenticator app, which is easier to govern as a controlled identity artefact.
Q: What breaks when MFA challenges can be reused or remain valid too long?
A: The control stops being a one-time verification step and becomes a reusable token that attackers can replay or brute-force. Long-lived challenges also expand the attack window after authentication, which defeats the purpose of second-factor assurance and weakens incident response evidence.
Q: How do you know if MFA is actually being enforced correctly?
A: You should see every sign-in path issuing, expiring, and consuming challenges exactly as designed, with failed attempts, resets, and re-enrollment events recorded in logs. If users can bypass the challenge, reuse an old code, or complete sign-in without a second factor, enforcement is failing.
Technical breakdown
TOTP vs SMS MFA in custom auth flows
TOTP and SMS both create a second factor, but they do not carry the same risk profile. TOTP uses a shared secret and a time-based code generated by an authenticator app, which makes the secret lifecycle central to security. SMS relies on carrier-delivered codes, which are easier to intercept through SIM swap, phishing, or malware. In a homegrown system, the important design choice is not just the factor type, but whether the application treats the factor as a durable identity object with strict enrollment, storage, and verification rules.
Practical implication: prefer TOTP as the default and reserve SMS for fallback only where business risk and user population justify it.
MFA challenge lifetimes, replay protection, and rate limiting
An MFA challenge is a short-lived assertion that a factor was presented successfully, but only if the system enforces expiry and one-time use. If the same challenge can be reused, or if verification attempts are unlimited, attackers gain a brute-force or replay path even when MFA is present. The guide’s 10-minute SMS expiry is an example of a time-bounded trust window, but the governance point is broader: each challenge must be consumed once, invalidated immediately, and protected by retry controls that make guessing impractical.
Practical implication: mark every successful challenge as consumed, enforce short lifetimes, and limit retries and cooldowns on verification endpoints.
Secrets handling around factor IDs, challenge IDs, and recovery flows
Homegrown MFA often fails at the storage boundary, not the verification API. Factor IDs, challenge IDs, TOTP secrets, and SMS-related tokens become sensitive identity artefacts once they are bound to a user session or enrolment flow. If those values appear in logs, client-side code, or loosely protected configuration, the MFA layer becomes easier to bypass or abuse. Secure handling means encrypted storage, controlled server-side access, and clear separation between user-facing data and internal identity state.
Practical implication: keep MFA artefacts server-side, encrypt them at rest, and prevent them from being written to logs, browser code, or shared config files.
Breaches seen in the wild
- Google Firebase misconfiguration breach — Firebase misconfigurations exposed 19.8M secrets across developer instances.
- Shai Hulud npm malware campaign — Shai Hulud campaign: npm malware exposed secrets on GitHub.
Read our 52 NHI Breaches Analysis report for a comprehensive view of breaches impacting Non-Human Identities including AI Agents.
NHI Mgmt Group analysis
Homegrown MFA is only as strong as the identity state behind it. The security control is not the challenge prompt, it is the governance around factor enrollment, expiry, replay, and storage. Once those states live inside application logic, the organisation owns the full lifecycle failure surface, from initial enrolment to reset and re-enrollment. Practitioners should treat MFA as an identity workflow with failure modes, not as a checkbox.
SMS-based MFA creates avoidable trust debt. SMS is operationally convenient, but it relies on a transport path that is vulnerable to SIM swap, phishing, and malware interception. That makes it a weak primary factor for environments that already hold sensitive data or privileged access. The field should read SMS as fallback recovery, not as a durable assurance layer, especially where account takeover would have broad blast radius.
Challenge expiry and one-time use are the real control boundary. A reusable or long-lived challenge turns MFA into a soft gate instead of a security boundary. Workflows that allow the same challenge ID to be verified twice, or that leave verification windows open too long, effectively widen the attack window after the user has already completed authentication. The practitioner conclusion is simple: lifecycle semantics matter as much as code execution.
Identity logging turns MFA from a feature into a governable control. Enrollment, challenge, verification, and reset events are the evidence trail that lets security teams detect abnormal behaviour. Without those records, organisations cannot distinguish normal user friction from replay, takeover attempts, or device churn. MFA programmes that lack auditability are hard to recertify, hard to investigate, and harder to defend under pressure.
Homegrown authentication increasingly behaves like NHI governance. The same programme that protects human login flows also needs to protect tokens, secrets, and machine-assisted flows that sit beside those accounts. That is why MFA design cannot be separated from broader identity governance. Teams should evaluate the integration as part of a wider access model, not as a standalone login enhancement.
From our research:
- 80% of identity breaches involved compromised non-human identities such as service accounts and API keys, according to Ultimate Guide to NHIs.
- Only 5.7% of organisations have full visibility into their service accounts, which means most identity teams cannot confidently inventory the non-human side of their access surface.
- The same governance gap appears in human-authentication programmes when factor state, challenge expiry, and recovery paths are not fully observable, as shown in the Ultimate Guide to NHIs.
What this signals
Challenge-bound authentication is becoming a governance issue, not a UX detail. Once MFA is embedded in application code, the programme inherits lifecycle obligations around enrolment, recovery, and revocation. Teams that already struggle with service account visibility should assume similar blind spots will appear in custom auth flows unless the identity state is modelled explicitly.
Factor recovery is the point where account security often degrades into account rescue. If reset flows are not tightly governed, the weakest recovery path becomes the true control plane for compromise. That is especially relevant for hybrid identity programmes where user access, shared secrets, and automated identity processes are managed through different teams and tools.
MFA should be evaluated alongside broader identity observability, not in isolation. The same programmes that cannot reliably track non-human access tend to miss weak signals in human-authentication flows, especially around device change, challenge failure, and re-enrollment. Teams looking for a practical reference point should pair implementation work with Ultimate Guide to NHIs and NIST Cybersecurity Framework 2.0.
For practitioners
- Prefer TOTP as the primary factor Use authenticator-app based TOTP for standard sign-in, and reserve SMS for recovery or exceptional enrolment paths. Make the default explicit in product and policy so weaker fallback methods do not become the primary assurance layer.
- Enforce single-use, short-lived challenges Set strict expiry on every challenge, invalidate it immediately after successful verification, and block additional use of the same challenge ID. Add rate limiting and cooldown periods to reduce brute-force attempts against verification endpoints.
- Protect MFA artefacts as sensitive identity state Store factor IDs, challenge IDs, and TOTP secrets server-side in encrypted storage, and keep them out of logs, browser code, and shared configuration. Treat them as governed identity data, not application metadata.
- Log enrollment and verification events Record who enrolled, when a challenge was issued, what factor type was used, and whether verification succeeded or failed. Use those logs to detect repeated failures, suspicious resets, and new-device enrolment patterns.
- Re-enrol factors after suspicious activity Force re-enrollment when users change password, change email, or show signs of device compromise. Tie re-enrollment to the account recovery policy so factor reset does not become an attacker-controlled bypass path.
Key takeaways
- Homegrown MFA is a lifecycle problem as much as a sign-in control, because enrollment, challenge validity, and recovery determine whether the factor is trustworthy.
- SMS should be treated as a fallback method, since transport weakness and interception risk make it a poor primary assurance layer for sensitive systems.
- Teams that cannot observe and govern MFA state should assume the same blind spots will affect adjacent identity controls, including secrets and non-human access.
Standards & Framework Alignment
This section maps relevant standards and security frameworks to the operational risks and controls described in this guidance.
OWASP Non-Human Identity Top 10 address the attack and risk surface, while NIST CSF 2.0 and NIST Zero Trust (SP 800-207) set the governance and control requirements practitioners need to meet.
| Framework | Control / Reference | Relevance |
|---|---|---|
| OWASP Non-Human Identity Top 10 | NHI-03 | MFA factor and challenge handling touches secret lifecycle and enforcement. |
| NIST CSF 2.0 | PR.AC-7 | MFA is an authentication control used to strengthen access enforcement. |
| NIST Zero Trust (SP 800-207) | PA | Homegrown MFA supports continuous verification in a zero-trust model. |
Treat MFA artefacts as governed NHI secrets and enforce rotation, expiry, and revocation.
Key terms
- Multi-Factor Authentication: Multi-Factor Authentication is an authentication method that requires more than one proof of identity before access is granted. In custom application flows, it becomes an identity workflow with enrolment, verification, expiry, recovery, and audit requirements that must be controlled like any other access state.
- TOTP: Time-based One-Time Password is a second factor that generates short-lived codes from a shared secret and the current time. It is commonly used with authenticator apps and is preferable to SMS when teams need a stronger, more governable second factor for user access.
- Challenge Expiry: Challenge expiry is the time limit placed on a verification attempt so the code or token cannot be reused later. In identity governance, expiry is a control on the trust window itself, reducing replay risk and limiting how long an attacker can work on a stolen or intercepted code.
- Factor Re-enrollment: Factor re-enrollment is the process of replacing a previously bound authentication factor with a new one after reset, device change, or suspicious activity. It is a lifecycle control that prevents recovery flows from becoming a bypass path and helps preserve assurance after compromise or device churn.
Deepen your knowledge
MFA integration, factor lifecycle, and challenge governance are core topics in our NHI Foundation Level course, the industry's only accredited NHI security programme. If you are building identity controls inside a homegrown auth flow, it is worth exploring.
This post draws on content published by WorkOS: How to add MFA to your homegrown auth using WorkOS. Read the original.
Published by the NHIMG editorial team on 2025-07-16.
NHI Mgmt Group — the independent authority on Non-Human Identity, IAM, and Agentic AI security. nhimg.org