Multi-Factor Authentication
Multi-factor authentication (MFA) can reduce account-takeover risk when an eligible sign-in path enforces a second proof after the primary credential. It is one control, not a guarantee against unauthorized access.
Classic factors are TOTP, email OTP, and provider-backed SMS OTP. Configured push approval is a separate factor path; passkeys are separate WebAuthn credentials, and backup codes are one-use recovery proofs.
Supported Methods
| Method | How It Works | Requirements |
|---|---|---|
| TOTP | Time-based codes generated by an authenticator app | An RFC 6238 client validated for your deployment |
| Email OTP | A bounded 6-digit code is requested for the verified email address | Verified email plus an eligible configured delivery path |
| SMS OTP | A bounded 6-digit code is requested through a configured SMS route | Verified phone plus a usable Twilio, AWS SNS, or MessageBird route |
| Push approval | A configured push route requests approval from an eligible enrolled device | Push enabled by policy, enrolled device, and usable delivery configuration |
| Passkey | RP- and origin-bound WebAuthn public-key authentication | Compatible browser and authenticator validated for the deployment |
Recommendation: Choose factors for the deployment's threat model. TOTP avoids email and SMS delivery dependencies; passkeys provide a separate RP-bound path. Store one-use backup codes securely for recovery.
Enabling MFA
Users enable MFA from their Account → Securitypage. Enrollment, verification, step-up, provider, browser, and policy requirements differ by factor path.
TOTP (Authenticator Apps)
TOTP uses a shared secret to generate 6-digit, 30-second codes under RFC 6238. The client generates codes locally; deployment owners must validate the intended authenticator versions and clock behavior.
Authenticator candidates to validate
- Google Authenticator (candidate; validate supported versions)
- Authy (candidate; validate supported versions)
- 1Password (candidate; validate supported versions)
- Microsoft Authenticator (candidate; validate supported versions)
- Another RFC 6238 client validated for the deployment
Setup Flow
- Navigate toAccount → Securityand clickEnable TOTP.
- UniAuth returns data.method, data.secret, and data.qrCode. Scan the QR image data or enter the secret manually; the setup response has no backupCodes field.
- Enter the 6-digit code currently shown in your authenticator app to verify the setup.
- When this is the first verified classic factor, the verification response may provide eight backup codesin XXXX-XXXX-XXXX-XXXX format. Store them safely; each replaces only the second-factor proof after the required primary credential.
API: Setup TOTP
POST /api/auth/2fa/setup
Content-Type: application/json
Cookie: auth_token=...
{
"method": "totp"
}
// Response (200):
{
"success": true,
"message": "2FA setup initiated",
"data": {
"method": "totp",
"secret": "BASE32SECRET",
"qrCode": "data:image/png;base64,..."
}
}API: Verify TOTP Setup
POST /api/auth/2fa/verify confirms enrollment only. It requires an auth_token cookie and step-up for 2fa.enable, with code and method in the body. It does not complete anonymous login.
- After data.requires2FA, complete password sign-in by posting email, password and twoFactorCode to /api/auth/login again. Use twoFactorMethod when selecting a method. No userId or pending-login token replaces the credentials; other required challenges, such as CAPTCHA, still apply.
- Apple and social sign-in use a separate pending credential: a browser cookie or a native pending credential (Apple returns applePendingToken; the continuation accepts it as pendingToken). Continue through /api/auth/social/2fa-options and /api/auth/social/2fa-verify; do not replace that flow with password login or /api/auth/2fa/verify.
POST /api/auth/2fa/verify # enrollment — caller is logged in
Content-Type: application/json
Cookie: auth_token=...
{
"code": "123456",
"method": "totp"
}
// Response (200), when this enrollment creates the account's first stored method row:
{
"success": true,
"message": "2FA method enabled successfully",
"data": {
"backupCodes": [
"A1B2-C3D4-E5F6-0718",
"192A-3B4C-5D6E-7F80",
"89AB-CDEF-0123-4567",
"FEDC-BA98-7654-3210",
"0A1B-2C3D-4E5F-6071",
"8192-A3B4-C5D6-E7F8",
"1357-9BDF-2468-ACE0",
"C0DE-FEED-5AFE-B00C"
],
"isFirstMethod": true
}
}Security: The server stores the TOTP secret with AES-256-GCM encryption and can decrypt it to verify codes. This is not end-to-end or zero-knowledge storage; the secret is returned during initial setup.
Email OTP
Eligible configured email-OTP paths can request a 6-digit code for your verified address. A generic acknowledgement proves neither an account, proof issuance, transport acceptance, nor delivery. The code is valid for 10 minutes and can be accepted only once before expiry.
How It Works
- An eligible password-login path can request a code after the primary credential.
- The generic request acknowledgement confirms neither an account, proof issuance, transport acceptance, nor delivery.
- Submit a received code; successful proof still remains subject to session-admission and policy checks.
Enabling Email OTP
Your email address must be verified before you can enable email OTP. Navigate to Account → Securityand select Enable Email OTP. Request and verify a code to confirm enrollment. Continue the authenticated email setup only when data.emailDispatchAccepted === true; this reports configured-transport acceptance, not inbox delivery.
API: Send Email Code
POST /api/auth/2fa/send-code
Content-Type: application/json
{
"email": "user@example.com",
"method": "email"
}
// Response (200):
{
"success": true,
"message": "Request processed",
"data": null
}Anonymous POST /api/auth/2fa/send-code accepts email and method (email or sms), not userId. Its generic Request processed response has data: null; it confirms neither an account, proof issuance, transport acceptance, nor delivery. Request another code only on a separate user action.
With an auth_token cookie, /api/auth/2fa/send-code instead authorizes a signed-in factor action using fresh, session-bound step-up for 2fa.disable. Send method, not another account’s email or userId. For email, advance only when data.emailDispatchAccepted === true; that means the configured transport accepted the request, not that a message reached an inbox.
Note: The OTP is stored with AES-256-GCM encryption. Expiry prevents acceptance; later cleanup is storage hygiene, not the validity boundary.
SMS OTP
An eligible configured SMS route can request a 6-digit code for your verified phone number. Provider acknowledgement is not proof of handset delivery. The code is valid for 10 minutes and can be accepted only once before expiry.
Prerequisites
- Your phone number must be verified in your security settings.
- The UniAuth instance needs a usable Twilio, AWS SNS, or MessageBird route. See the Configuration guide for provider and routing configuration.
Enabling SMS OTP
- Go toAccount → Security.
- Add and verify your phone number if you haven't already.
- ClickEnable SMS OTP.
- If a code arrives, submit it to confirm setup; the request acknowledgement alone is not delivery proof.
API: Send SMS Code
POST /api/auth/2fa/send-code
Content-Type: application/json
{
"email": "user@example.com",
"method": "sms"
}
// Response (200):
{
"success": true,
"message": "Request processed",
"data": null
}Anonymous POST /api/auth/2fa/send-code accepts email and method (email or sms), not userId. Its generic Request processed response has data: null; it confirms neither an account, proof issuance, transport acceptance, nor delivery. Request another code only on a separate user action.
Note: SMS has carrier, routing, interception, and SIM-swap risks. After selecting a provider, UniAuth does not automatically retry a failed dispatch through another provider. If no usable route can be selected, this factor is unavailable.
Configured Push Approval
Push is disabled by default. It is offered only when policy enables it, an eligible enrolled device exists, and delivery is configured.
An approval remains subject to challenge, expiry, device, policy, and session-admission checks. Initial push enrollment may issue backup codes when no usable set already exists.
Default Method
On an eligible first-party password login, UniAuth offers the first usable default classic or configured push factor. Switching to another listed factor does not guarantee provider availability or delivery.
Set your default method in Account → Security, or via the API:
POST /api/auth/2fa/set-default
Content-Type: application/json
Cookie: auth_token=...
{
"method": "push" // "totp", "email", "sms", or "push"
}
// Response (200):
{
"success": true,
"message": "Push approval set as default",
"data": null
}Using Multiple Methods
Classic TOTP, email OTP, and SMS OTP factors may coexist; configured push is separate. Availability and delivery remain path- and provider-dependent:
- UseTOTPwhen you want locally generated codes without a message-delivery dependency.
- Keepemail OTPonly where the verified address and configured delivery path are usable.
- AddSMS OTPonly where the verified phone and configured provider route are usable.
The verification screen can offer another eligible factor. Selecting email, SMS, or push starts that factor's own checks and does not promise message delivery or approval.
Verification During Login
These examples describe UniAuth’s first-party, same-origin sign-in UI, not an integration API. Third-party apps must use hosted OAuth/OIDC Authorization Code with PKCE; they must not collect UniAuth passwords.
An eligible first-party password login that requires MFA has at least these stages:
- Password verification — Submit email and password as usual. The API responds with a 2FA challenge instead of completing login.
- MFA verification — Submit the selected factor proof; codes, push approval, and backup recovery use distinct paths.
Step 1: Login Returns a 2FA Challenge
POST /api/auth/login
Content-Type: application/json
{
"email": "user@example.com",
"password": "your-password"
}
// Response when 2FA is enabled (200):
{
"success": true,
"message": "2FA code required",
"data": {
"requires2FA": true,
"twoFactorMethod": "totp",
"enabledMethods": ["totp", "email", "sms", "push", "backup"]
}
}The response includes the user's preferred 2FA method (twoFactorMethod) and all enabled methods (enabledMethods) for UniAuth’s verification screen. Password login returns neither userId nor a pending-login credential; submit the credentials again with the selected classic or backup proof.
Step 2: Submit the Verification Code
After data.requires2FA, complete password sign-in by posting email, password and twoFactorCode to /api/auth/login again. Use twoFactorMethod when selecting a method. No userId or pending-login token replaces the credentials; other required challenges, such as CAPTCHA, still apply.
// Optional email/SMS resend; the initial password challenge may send a code:
POST /api/auth/2fa/send-code
Content-Type: application/json
{
"email": "user@example.com",
"method": "email"
}
// Submit credentials again with the selected factor's code:
POST /api/auth/login
Content-Type: application/json
{
"email": "user@example.com",
"password": "your-password",
"twoFactorCode": "123456",
"twoFactorMethod": "email"
}
// Success response (200):
{
"success": true,
"message": "Login successful",
"data": {
"authenticated": true,
"user": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"email": "user@example.com",
"firstName": "Jane",
"lastName": "Doe"
}
}
}A valid factor proof does not by itself establish session admission. Continue only when the final response reports data.authenticated === true and all policy checks succeed.
For Developers: Integrating MFA
These examples describe UniAuth’s first-party, same-origin sign-in UI, not an integration API. Third-party apps must use hosted OAuth/OIDC Authorization Code with PKCE; they must not collect UniAuth passwords.
Detecting a 2FA Challenge
After submitting credentials, check the response for the requires2FA flag:
// UniAuth's same-origin first-party UI only.
async function login(email, password) {
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
const data = await res.json();
if (res.ok && data.success && data.data?.requires2FA) {
// Show the 2FA verification screen
show2FAScreen({
twoFactorMethod: data.data.twoFactorMethod,
enabledMethods: data.data.enabledMethods,
});
return;
}
if (res.ok && data.success && data.data?.authenticated === true) {
// Login complete — no 2FA required
redirectToDashboard(data.data.user);
}
}Completing 2FA Verification
// UniAuth's same-origin first-party UI only; resend is a separate user action.
async function requestCode(email, method) {
const res = await fetch('/api/auth/2fa/send-code', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, method }),
});
return res.json(); // Generic acknowledgement, never proof of delivery.
}
async function verify2FA(email, password, code, method) {
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email, password, twoFactorCode: code, twoFactorMethod: method
}),
});
const data = await res.json();
if (res.ok && data.success && data.data?.authenticated === true) {
redirectToDashboard(data.data.user);
} else {
handleLoginChallengeOrError(data);
}
}A successful HTTP response or success: true alone does not establish a session. Password login is complete only when data.authenticated is true; handle remaining challenges and errors before continuing.
Error Handling
This table combines enrollment/setup routes with the first-party password-login route. Interpret each status only for the route named in its row.
| Status | Meaning | Action |
|---|---|---|
200 | Request acknowledged; authentication may still be pending | Password login completes only with data.authenticated: true, not a resend acknowledgement |
400 | /api/auth/2fa/verify: invalid or expired enrollment proof; setup routes: malformed or unsupported request | For /api/auth/2fa/verify, restart enrollment with a current proof; for setup routes, correct the request shape or selected method |
401 | /api/auth/login password login: invalid factor proof or generic authentication rejection, including lockout | On /api/auth/login, show the generic response; do not infer whether an account or factor exists |
429 | Rate limited | Honor the response and configured rate-limit window before retrying |
Backup Codes
Eight formatted one-use backup codes may be issued after the first verified classic factor, or after push enrollment when no usable set exists. A backup code replaces only the second-factor proof after the required primary credential.
- Each backup code can only be usedonce.
- Backup codes are stored as a keyed hash (HMAC-SHA256), never in plaintext, so a copy of the database alone does not yield working codes — and UniAuth cannot recover them for you.
- Store them in a password manager, printed on paper in a safe location, or in an encrypted note.
- You can regenerate a new set of backup codes from your security settings (this invalidates all previous codes).
Important: Treat backup codes as authentication secrets. Each XXXX-XXXX-XXXX-XXXX code is HMAC-protected and consumed atomically once; regenerate the set if exposure is suspected.
Best Practices
- Choose factors for the threat model. TOTP avoids message delivery but remains a shared-secret code; validate clients, storage, clocks, and recovery.
- Validate every recovery path. Email, SMS, push, and backup recovery have distinct delivery, device, provider, and policy boundaries.
- Store backup codes securely. Save them in your password manager or print them and keep them in a secure physical location.
- Avoid SMS as your only method. SMS carries SIM-swap, routing, delivery, and carrier-interception risks; assess those risks for the deployment.
- Evaluate passkeys separately. For an RP- and origin-bound public-key path, evaluate passkey authentication, including the exact browser, authenticator, origin, RP ID, and recovery profile.
Disabling MFA
You can disable individual MFA methods or all of them from Account → Security. Disabling requires fresh session-bound step-up; a password-only step-up also requires a current factor or backup proof.
Removing a classic or push factor preserves existing backup codes while another classic or push factor remains; removing the last such factor clears the backup-code set. Separate passkeys and the recovery phrase are not changed by this route.
Tip: If you cannot satisfy an enrolled factor or backup proof, an authorized administrator can perform a guarded MFA reset from the Admin Panel. The reset retires classic and push factors plus prior backup codes, preserves separate passkeys and the recovery phrase, and issues a one-time recovery credential; it is not temporary disablement.