2FA for AI Platforms: TOTP, WebAuthn, and Enforcement
TL;DR — 2FA is non-negotiable for enterprise AI platforms. Passwords alone cannot protect systems where a single session can trigger agent deployments, access PII, and execute financial transactions. Implement TOTP as the baseline, offer WebAuthn/FIDO2 passkeys as the preferred method, and avoid SMS entirely. Enforce 2FA per-tenant with configurable policies. Add step-up authentication for sensitive agent actions — a valid session is not enough when the action can cause irreversible damage. Generate backup codes at enrollment, design a secure recovery flow, and verify 2FA completion at the platform layer, not just the IdP.
Why AI Platforms Need 2FA
A compromised password on a traditional SaaS app might expose some data. A compromised password on an AI platform can cause an autonomous agent to send emails, modify production data, access confidential documents, and execute API calls against third-party services — all within seconds.
AI platforms amplify the blast radius of a single stolen credential. One authenticated session can:
- Deploy or modify AI agents that act on behalf of the user
- Access connected data sources (Google Drive, Slack, internal wikis) via OAuth tokens stored by the platform
- Execute LLM API calls that consume budget and leak sensitive prompts
- Modify billing settings and payment methods
- Export training data or conversation logs containing PII
Password-only authentication is insufficient. Enterprise customers know this — 2FA is a hard requirement in every enterprise security review. The question is not whether to implement 2FA, but how to implement it correctly for the unique risks of AI platforms.
2FA Methods: A Hierarchy of Security
TOTP (Time-Based One-Time Passwords)
TOTP is the workhorse of 2FA. The user scans a QR code with an authenticator app (Google Authenticator, Authy, 1Password), and the app generates a 6-digit code every 30 seconds using a shared secret and the current time.
How it works:
- Platform generates a random 160-bit secret
- Secret is encoded as a QR code (otpauth:// URI)
- User scans the QR code with their authenticator app
- At login, user enters the current 6-digit code
- Platform recomputes the code from the stored secret and verifies it matches
Pros: Works offline, no phone number required, supported by every authenticator app, RFC 6238 standard.
Cons: Not phishing-resistant (users can be tricked into entering TOTP codes on fake sites), secret must be stored securely on the platform side, users can lose access if they lose their phone.
Implementation note: Store the TOTP secret encrypted at rest using the same encryption infrastructure you use for API keys (Fernet or envelope encryption). Never store TOTP secrets in plaintext.
WebAuthn / FIDO2 Passkeys
WebAuthn is the gold standard for authentication in 2026. It uses public-key cryptography — the authenticator (hardware key or platform authenticator like Touch ID/Windows Hello) signs a challenge from the server, proving possession of the private key without ever exposing it.
How it works:
- During registration, the authenticator generates a key pair and sends the public key to the platform
- At login, the platform sends a random challenge
- The authenticator signs the challenge with the private key
- The platform verifies the signature using the stored public key
Pros: Phishing-resistant (the authenticator checks the origin), no shared secret to steal, no code to intercept, user-friendly (biometric unlock).
Cons: Requires device enrollment, harder to implement than TOTP, recovery is more complex (need backup authenticators).
Implementation note: Use the webauthn library for your language. Support both platform authenticators (Touch ID, Windows Hello) and roaming authenticators (YubiKey). Store credential IDs and public keys per user, allow multiple registered credentials for redundancy.
Push Notifications
Push-based 2FA sends a notification to the user's phone via a mobile app. The user approves or denies the login attempt. Solutions like Cisco Duo, Okta Verify, and Microsoft Authenticator offer this.
Pros: Better UX than typing codes, can display context (location, device, browser).
Cons: Requires a mobile app installed, vulnerable to push fatigue (users approve without reading), depends on internet connectivity.
Implementation note: If using push, implement number-matching — display a number on the login screen and ask the user to select the matching number in the app. This defeats push fatigue attacks.
SMS (Do Not Use)
SMS-based 2FA is vulnerable to SIM-swapping attacks, where an attacker social-engineers the carrier into transferring the victim's phone number to a new SIM. SMS can also be intercepted via SS7 vulnerabilities.
Recommendation: Do not offer SMS as a 2FA option. If enterprise customers see SMS in your security questionnaire, they will flag it as a risk. If you must offer it as a last-resort fallback, clearly label it as insecure and require admin approval to enable.
Per-Tenant MFA Enforcement
In a multi-tenant AI platform, different tenants have different security requirements. A healthcare tenant may require WebAuthn-only. A startup tenant may want TOTP as optional. The platform must support per-tenant MFA policies.
Policy Configuration
Each tenant admin configures MFA policies through the platform's admin panel:
# Example per-tenant MFA policy
mfa_policy:
required: true # Is 2FA mandatory for all users?
allowed_factors:
- webauthn # Preferred
- totp # Baseline
preferred_factor: webauthn # Show this first during enrollment
session_timeout_minutes: 480 # Re-auth after 8 hours
step_up_required_actions:
- delete_agent
- modify_billing
- export_data
- modify_data_source
enrollment_grace_period_days: 7 # Users have 7 days to enroll
Enforcement Points
The platform enforces MFA at three levels:
-
Login enforcement: After SSO authentication, check the tenant's MFA policy. If 2FA is required and the user has not completed it, challenge them before creating a session. Do not trust the IdP's MFA claim alone — the platform must verify its own 2FA completion.
-
Session validation: Every request checks that the session has a valid MFA timestamp. If the session's MFA has expired (based on
session_timeout_minutes), require re-authentication. -
Step-up enforcement: Before executing sensitive actions listed in
step_up_required_actions, require a fresh 2FA challenge regardless of session age.
Enrollment Flow
When a tenant enables mandatory 2FA:
- Admin enables the policy and sets a grace period (e.g., 7 days)
- All users in the tenant see a banner: "2FA enrollment required by [date]"
- Users who have not enrolled by the deadline are locked out
- Admins can extend the grace period or manually exempt specific users
- The platform logs all enrollment events for audit purposes
Step-Up Authentication for AI Agent Actions
This is the key differentiator for AI platforms. Traditional SaaS apps need 2FA at login. AI platforms need 2FA at action time.
The Problem
A user logs in with 2FA at 9 AM. Their session is valid for 8 hours. At 2 PM, an attacker who has stolen the session cookie can:
- Delete all AI agents
- Disconnect data sources
- Export conversation logs containing PII
- Modify billing settings
- Change admin permissions
The original 2FA at login does not protect against this. The session is valid, and the platform has no way to distinguish the legitimate user from the attacker.
The Solution: Step-Up Authentication
Step-up authentication requires a fresh 2FA challenge before sensitive actions, regardless of session age.
async def execute_sensitive_action(action: str, user: User, session: Session):
# Check if action requires step-up
if action in SENSITIVE_ACTIONS:
# Check if session has a recent step-up
if not session.has_recent_step_up(within_minutes=5):
# Return a challenge instead of executing
return StepUpChallenge(
challenge_id=generate_challenge_id(),
available_factors=user.get_enrolled_factors(),
action=action,
)
# Step-up verified (or not required) — proceed
return await perform_action(action, user)
Sensitive Actions Requiring Step-Up
For AI platforms, these actions should always require step-up:
- Deleting or modifying AI agents — agents may have access to sensitive data sources
- Adding or removing data source connections — OAuth tokens grant broad access
- Exporting conversation logs or training data — may contain PII
- Modifying billing or payment methods — financial risk
- Changing admin roles or permissions — privilege escalation
- Accessing raw PII in search results or document previews
- Executing API calls to third-party services via agent workflows
Implementation
- Define a
SENSITIVE_ACTIONSset per tenant (configurable) - Track
last_step_up_aton the session object - Before executing a sensitive action, check if step-up was completed within the last N minutes (default: 5)
- If not, return a 2FA challenge (TOTP code entry or WebAuthn assertion)
- On successful verification, update
last_step_up_atand proceed - Rate-limit step-up attempts to prevent brute force
2FA Recovery: The Weakest Link
The recovery flow is where most 2FA implementations fail. If an attacker can bypass 2FA through recovery, the 2FA is theater.
Backup Codes
At enrollment, generate 10 single-use backup codes:
import secrets
import string
def generate_backup_codes(count: int = 10) -> list[str]:
chars = string.ascii_uppercase + string.digits
return [
''.join(secrets.choice(chars) for _ in range(8))
for _ in range(count)
]
- Store backup codes hashed (bcrypt or Argon2), never in plaintext
- Display once at enrollment and let the user download them
- Each code is single-use — mark as consumed after verification
- Allow regeneration (requires current 2FA verification)
Admin-Assisted Reset
For enterprise tenants, admins can reset a user's 2FA:
- Admin initiates reset from the admin panel
- Platform sends a reset link to the user's verified email
- Reset link is valid for 1 hour and single-use
- User clicks the link and re-enrolls a new 2FA factor
- All existing sessions are invalidated
- The action is logged for audit
Critical: Admin-assisted reset must require step-up authentication for the admin. Do not allow admins to reset 2FA without re-verifying their own identity.
What Not to Do
- Do not allow email-only recovery — if the email is compromised, 2FA is bypassed
- Do not allow security questions — they are weaker than passwords
- Do not allow SMS recovery — same SIM-swapping risk
- Do not allow unlimited recovery attempts — rate-limit aggressively
- Do not allow recovery without invalidating all existing sessions
Verifying 2FA at the Platform Layer
A common mistake: trusting the IdP's MFA claim without verification.
When a user authenticates via SSO (SAML or OIDC), the IdP may include an mfa_verified claim. Some platforms see this and skip their own 2FA enforcement. This is dangerous:
- The IdP's MFA policy may differ from the tenant's policy. The IdP may accept SMS; the tenant requires WebAuthn.
- The IdP's MFA may have expired. The SSO session might be hours old, but the tenant requires step-up for sensitive actions.
- The IdP claim could be spoofed in misconfigured SAML setups.
Correct Approach
The platform should treat SSO as the first factor. The platform's own 2FA is the second factor, enforced according to the tenant's policy:
- User authenticates via SSO (first factor)
- Platform checks tenant's MFA policy
- If 2FA is required and the user has enrolled factors, challenge for 2FA
- If 2FA is required and the user has no enrolled factors, redirect to enrollment
- On successful 2FA, create a session with
mfa_verified_attimestamp - Enforce step-up for sensitive actions based on tenant policy
This does not mean users authenticate twice every time. If the tenant trusts the IdP's MFA, the platform can accept the mfa_verified claim and set mfa_verified_at accordingly. But the platform must still enforce its own step-up authentication for sensitive actions — the IdP cannot do this.
Session Management After 2FA
2FA is only as strong as the session it protects. If a session token is stolen after 2FA, the attacker has full access until the token expires.
Session Properties
class Session:
user_id: str
tenant_id: str
mfa_verified_at: datetime # When 2FA was completed
mfa_expires_at: datetime # When 2FA expires (re-auth required)
last_step_up_at: datetime | None # Last step-up challenge time
ip_address: str
user_agent: str
device_fingerprint: str
Session Security Rules
- Short MFA expiry: Set
mfa_expires_atto 8-12 hours. After this, require re-authentication even if the session is technically valid. - IP binding: If the IP address changes significantly (different ASN, different country), invalidate the session.
- Device fingerprinting: Bind sessions to a device fingerprint. If the fingerprint changes, require re-authentication.
- Server-side revocation: Store sessions server-side, not just in JWTs. Allow instant revocation when a user reports a compromised account.
- Concurrent session limits: Limit the number of active sessions per user (e.g., 5). When a new session is created, the oldest is revoked.
Monitoring and Audit
Enterprise customers require evidence that 2FA is enforced. The platform must log:
- Enrollment events: User ID, factor type, timestamp, IP
- Authentication events: User ID, factor used, success/failure, timestamp, IP
- Step-up events: User ID, action attempted, factor used, success/failure
- Recovery events: User ID, method used (backup code, admin reset), timestamp
- Policy changes: Admin ID, old policy, new policy, timestamp
These logs must be tamper-proof, exportable, and retained according to the tenant's compliance requirements (typically 1-7 years).
Alerting
Set up alerts for:
- Repeated 2FA failures from the same IP (brute force attempt)
- 2FA recovery attempts from new locations
- Mass 2FA reset requests (potential admin account compromise)
- Step-up failures on sensitive actions
- Users disabling 2FA (if policy allows optional 2FA)
Enterprise Integration
SSO + 2FA Coexistence
When a tenant uses SSO (SAML/OIDC), the IdP typically enforces its own MFA. The platform should:
- Accept the IdP's MFA as the first 2FA layer
- Allow the tenant to configure whether platform-level 2FA is also required
- Always enforce platform-level step-up for sensitive actions, regardless of IdP MFA
- Log both the IdP MFA event and any platform MFA events
SCIM + 2FA
When users are provisioned via SCIM, they arrive without 2FA enrolled. The platform should:
- Mark SCIM-provisioned users as
mfa_enrollment_required - Redirect them to 2FA enrollment at first login
- Apply the tenant's grace period policy
- Notify the user via email that 2FA enrollment is required
API Keys and Service Accounts
2FA applies to human users. API keys and service accounts use a different mechanism:
- Short-lived tokens with automatic rotation
- IP allowlisting for service-to-service calls
- Scope-limited permissions — service accounts never get admin scope
- Audit logging for all API key actions
Do not try to apply 2FA to service accounts. Instead, use mTLS or signed JWTs for machine authentication.
Implementation Checklist
- [ ] Implement TOTP enrollment and verification (RFC 6238)
- [ ] Implement WebAuthn registration and authentication
- [ ] Generate and store backup codes (hashed, single-use)
- [ ] Implement per-tenant MFA policy configuration
- [ ] Enforce 2FA at login based on tenant policy
- [ ] Implement step-up authentication for sensitive actions
- [ ] Track
mfa_verified_atandlast_step_up_aton sessions - [ ] Implement admin-assisted 2FA reset with step-up
- [ ] Invalidate all sessions on 2FA reset
- [ ] Log all 2FA events (enrollment, auth, step-up, recovery)
- [ ] Set up alerting for brute force and suspicious recovery
- [ ] Rate-limit 2FA challenges and recovery attempts
- [ ] Store TOTP secrets and WebAuthn credentials encrypted at rest
- [ ] Do not offer SMS as a 2FA factor
- [ ] Verify 2FA at the platform layer, not just trust IdP claims
- [ ] Support concurrent session limits
- [ ] Bind sessions to IP and device fingerprint
- [ ] Allow per-tenant configuration of sensitive actions list
- [ ] Integrate with SCIM for enrollment-required flagging
- [ ] Export 2FA audit logs for compliance reporting
Conclusion
2FA for AI platforms is not just login security — it is action security. The unique risk of AI platforms is that a single compromised session can trigger autonomous agents, access connected data sources, and execute irreversible actions. Traditional login-time 2FA is necessary but insufficient.
Implement TOTP as the baseline. Offer WebAuthn passkeys as the preferred method. Avoid SMS entirely. Enforce per-tenant MFA policies with configurable factors and session timeouts. Add step-up authentication for every sensitive action — this is the single most important security control for AI platforms. Design a recovery flow that does not undermine 2FA. Verify 2FA at the platform layer, not just the IdP. Log everything.
Enterprise customers will ask about every one of these controls in their security review. Having clear, well-implemented answers is the difference between closing the deal and stalling in procurement.