Oauth2.0 and OpenIdConnect

TOTP Authentication

Overview

Time-Based One-Time Password (TOTP) is a widely adopted multi-factor authentication mechanism that generates temporary, time-synchronized codes on a user's device. TOTP provides a second authentication factor by requiring users to prove possession of a physical device (smartphone, hardware token) in addition to their primary credential (password or other first factor).

TOTP is defined in RFC 6238 and builds upon HMAC-based One-Time Password (HOTP) defined in RFC 4226. Unlike static passwords, TOTP codes expire every 30 seconds, making them resistant to replay attacks and significantly more secure than password-only authentication.

What TOTP Solves

Before TOTP and multi-factor authentication became widespread, user accounts relied solely on passwords for security. This single-factor approach created critical vulnerabilities:

Password Reuse: Users often reuse passwords across multiple services, meaning a breach at one service compromises accounts elsewhere.

Phishing Attacks: Attackers could steal passwords through social engineering, and those credentials remained valid indefinitely.

Credential Stuffing: Stolen password databases enabled automated attacks against multiple services.

Weak Passwords: Users frequently chose weak, easily guessable passwords for convenience.

TOTP addresses these issues by adding a second factor that requires physical possession of a device. Even if an attacker steals a user's password, they cannot authenticate without also accessing the user's authenticator device. This dramatically reduces the risk of account compromise from password-related attacks.

Core Concepts

The Two-Factor Principle

TOTP implements the security principle of "something you know" (password) plus "something you have" (authenticator device). This combination ensures that authentication requires both knowledge and physical possession, making unauthorized access significantly more difficult.

Something You Know: The user's password or other primary credential that can be memorized.

Something You Have: The physical device (smartphone, hardware token) that generates TOTP codes.

Time Synchronization: Both the authentication server and the user's device must have reasonably accurate clocks to generate matching codes.

TOTP as a Second Factor

TOTP is explicitly designed as a second authentication factor, not a standalone authentication method. While TOTP codes prove device possession, they don't establish identity on their own. TOTP must always be combined with a primary authentication factor.

Valid Primary Factors for TOTP:

  • Password authentication (traditional username/password)
  • Email-based OTP (one-time password sent via email)
  • SMS-based OTP (one-time code sent via text message)
  • Biometric authentication (in device-local scenarios)

Why TOTP Requires a First Factor: TOTP codes rotate every 30 seconds and are generated algorithmically from a shared secret. Without a first factor to establish identity, anyone with access to the shared secret could generate valid codes. The first factor ensures that only the legitimate account owner can proceed to the TOTP verification step.

Authentication Flow

A complete TOTP authentication flow consists of two distinct phases:

Phase 1: Primary Authentication

  1. User provides their primary credential (username/password, email OTP, etc.)
  2. System verifies the primary credential
  3. User proceeds to second-factor verification only after successful primary authentication

Phase 2: TOTP Verification

  1. User opens their authenticator app
  2. Authenticator generates a current 6-digit TOTP code
  3. User enters the code into the application
  4. System validates the code against the stored shared secret
  5. Authentication completes successfully if the code matches

How TOTP Works

The Algorithm

TOTP generates one-time passwords through a cryptographic process involving a shared secret, the current time, and HMAC-SHA1 hashing.

Step-by-Step Process:

  1. Time Step Calculation: The current Unix timestamp is divided by 30 seconds to create a time step counter. This means codes change every 30 seconds.
  2. Counter Encoding: The time step is encoded as an 8-byte big-endian integer.
  3. HMAC Generation: The encoded counter and the shared secret are processed through HMAC-SHA1 to produce a 20-byte hash.
  4. Dynamic Truncation: The algorithm extracts 4 bytes from the hash using a process called dynamic truncation, which uses the last 4 bits of the hash to determine an offset.
  5. Code Generation: The extracted 4 bytes are converted to an integer, reduced modulo 1,000,000, and formatted as a 6-digit code with leading zeros if necessary.

Mathematical Representation:

Time Step = floor(Unix Timestamp / 30)
HMAC Result = HMAC-SHA1(Secret Key, Time Step)
Offset = Last 4 bits of HMAC Result
Code Bytes = 4 bytes from HMAC Result starting at Offset
Code = (Code Bytes as Integer) mod 1,000,000

Shared Secret

The shared secret is the cryptographic key that both the authentication server and the user's authenticator app must possess to generate matching codes.

Secret Key Properties:

  • Typically 160 bits (20 bytes) in length
  • Generated using a cryptographically secure random number generator
  • Must be kept confidential and transmitted securely during setup
  • Stored encrypted in both the server database and the authenticator app
  • Should never be transmitted after initial setup

Security Considerations:

  • Each user account has a unique shared secret
  • Secrets should never be reused across accounts or services
  • Server-side storage must encrypt secrets at rest
  • Compromise of the shared secret allows code generation by attackers

Time Synchronization

TOTP relies on time synchronization between the server and the authenticator device to generate matching codes.

Time Window: Most implementations accept codes from the current time step as well as one step before and one step after (±30 seconds) to account for:

  • Clock drift between server and device
  • Network latency during code verification
  • User delays in entering the code

Synchronization Tolerance:

  • Standard tolerance: ±1 time step (90-second total window)
  • More lenient systems may allow ±2 steps (150-second window)
  • Overly generous windows reduce security by allowing replay attacks

Handling Clock Skew: Systems can track successful authentication patterns to detect and compensate for consistent clock drift on specific devices.

Setup Process

Initial Configuration

Setting up TOTP authentication requires securely sharing the secret key between the authentication server and the user's authenticator app.

Server-Side Setup:

  1. Generate a cryptographically random 160-bit secret key
  2. Encode the secret using Base32 for human readability
  3. Create a TOTP URI containing the secret, issuer name, and account identifier
  4. Generate a QR code from the TOTP URI for easy scanning
  5. Store the encrypted secret in the user database
  6. Display the QR code and manual entry key to the user

Client-Side Setup:

  1. User opens their authenticator app (Google Authenticator, Microsoft Authenticator, Authy, etc.)
  2. User scans the QR code or manually enters the Base32-encoded secret
  3. Authenticator app generates and displays the first TOTP code
  4. User enters the code to verify successful configuration
  5. Server validates the code and confirms TOTP activation

QR Code Format

TOTP configuration uses the otpauth:// URI scheme for standardized QR code generation.

URI Structure:

otpauth://totp/Issuer:[email protected]?secret=BASE32SECRET&issuer=Issuer&digits=6&period=30

URI Components:

Protocol: otpauth://totp/ - Indicates TOTP protocol (not HOTP)

Label: Issuer:[email protected] - Display name in authenticator app

  • Format: Issuer:AccountIdentifier
  • Issuer should be the application or service name
  • AccountIdentifier typically the user's email or username

Parameters:

  • secret: Base32-encoded shared secret (required)
  • issuer: Service name matching the label prefix (required)
  • digits: Code length, typically 6 (optional, default: 6)
  • period: Time step in seconds (optional, default: 30)
  • algorithm: Hash algorithm (optional, default: SHA1)

Example:

otpauth://totp/MyApp:[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=MyApp&digits=6&period=30

Base32 Encoding

TOTP secrets use Base32 encoding (RFC 3548) to make them human-readable and manually enterable if QR code scanning isn't available.

Base32 Characteristics:

Character Set: ABCDEFGHIJKLMNOPQRSTUVWXYZ234567 (32 characters)

  • Uses uppercase letters A-Z
  • Uses digits 2-7 (avoiding 0, 1, 8, 9 to prevent confusion with letters)
  • Case-insensitive for user convenience

Padding: Uses = characters for padding, though many implementations omit padding

Example Encoding:

  • Binary: 01001000 01100101 01101100 01101100 01101111 (Hello)
  • Base32: JBSWY3DPEBLW64TMMQ======

Advantages Over Base64:

  • No special characters that might be confused in manual entry
  • Case-insensitive reduces entry errors
  • Avoids ambiguous characters (0/O, 1/I/l)

Security Considerations

Attack Vectors

Phishing Attacks: Attackers may create fake login pages to capture both passwords and TOTP codes. However, TOTP codes expire quickly (30 seconds), limiting the window for successful phishing.

Man-in-the-Middle Attacks: If communications aren't encrypted with TLS, attackers could intercept TOTP codes. Always require HTTPS for authentication endpoints.

Secret Key Compromise: If the shared secret is exposed, attackers can generate valid codes indefinitely. Secrets must be:

  • Generated using cryptographically secure random number generators
  • Transmitted only during initial setup over encrypted channels
  • Stored encrypted in databases
  • Never logged or displayed after initial setup

Social Engineering: Attackers may trick users into revealing TOTP codes through phone calls or fake support requests. User education is critical.

Device Theft: If an attacker physically steals the user's authenticator device, they can generate codes. This risk is mitigated by device-level security (PINs, biometrics) and proper use of recovery codes.

Recovery Mechanisms

Recovery codes provide a fallback authentication method when users lose access to their TOTP authenticator device.

Recovery Code Properties:

  • Typically 10 single-use codes generated during TOTP setup
  • Each code is cryptographically random (usually 8-16 characters)
  • Stored as salted hashes in the database (like passwords)
  • Can only be used once, then permanently invalidated
  • Should be stored securely offline by the user (printed, password manager)

Recovery Flow:

  1. User attempts to log in but cannot access authenticator device
  2. User selects "Use recovery code" option
  3. User enters one of their saved recovery codes
  4. System validates and consumes the code
  5. User gains access and should immediately set up new TOTP authenticator

Best Practices:

  • Generate codes during initial TOTP setup
  • Force users to acknowledge and save codes before completing setup
  • Allow users to regenerate recovery codes (invalidating old ones)
  • Display remaining recovery code count to users
  • Send alerts when recovery codes are used
  • Recommend regenerating codes after use

Rate Limiting

Rate limiting is essential to prevent brute-force attacks against TOTP codes.

Implementation Strategies:

Per-Account Limiting: Limit verification attempts per user account

  • Typical limit: 5-10 attempts per hour
  • Lock account temporarily after threshold exceeded
  • Send security alerts on multiple failed attempts

Per-IP Limiting: Limit verification attempts from a single IP address

  • Prevents distributed attacks across multiple accounts
  • Typical limit: 50-100 attempts per hour per IP
  • Use with caution to avoid blocking legitimate traffic

Progressive Delays: Increase delay between attempts after failures

  • First failure: no delay
  • Second failure: 2-second delay
  • Third failure: 5-second delay
  • Fourth+ failures: 10-second delay

Account Lockout: Temporarily disable TOTP verification after excessive failures

  • Lock duration: 15-60 minutes
  • Require email verification to unlock
  • Log and alert on lockout events

Time Window Considerations

The time window for accepting TOTP codes represents a security trade-off between usability and security.

Standard Window (±1 step / 90 seconds total):

  • Accepts codes from: current, previous, and next 30-second periods
  • Balances security and usability
  • Recommended for most applications

Strict Window (0 steps / 30 seconds total):

  • Accepts only current 30-second period codes
  • Maximum security but poor user experience
  • May cause frequent authentication failures
  • Only suitable for high-security, low-volume scenarios

Lenient Window (±2 steps / 150 seconds total):

  • Accepts codes from 5 time periods
  • Better usability but reduced security
  • May be necessary for environments with significant clock drift
  • Increases replay attack window

Clock Skew Tracking: Advanced implementations track which time window codes come from and adjust for consistent device clock drift.

Implementation Best Practices

Server-Side Implementation

Secret Generation:

1. Use cryptographically secure random number generator
2. Generate 20 bytes (160 bits) of random data
3. Encode using Base32 for storage and display
4. Never reuse secrets across accounts

Secret Storage:

1. Encrypt secrets at rest using AES-256 or similar
2. Use separate encryption keys for different data types
3. Rotate encryption keys periodically
4. Never log or display secrets after initial setup
5. Use parameterized queries to prevent SQL injection

Code Verification:

1. Retrieve and decrypt user's shared secret
2. Calculate current time step
3. Generate codes for current, previous, and next time steps
4. Compare user-provided code against all three using constant-time comparison
5. Track which time window was used for clock skew compensation
6. Invalidate codes immediately after successful use (if implementing single-use codes)
7. Implement rate limiting before verification
8. Log verification attempts (success and failure)

Security Headers:

1. Require TLS 1.2+ for all authentication endpoints
2. Implement Content-Security-Policy headers
3. Use Strict-Transport-Security (HSTS)
4. Enable X-Frame-Options to prevent clickjacking
5. Implement X-Content-Type-Options: nosniff

Client-Side Implementation

Authenticator App Selection: Recommend established, well-audited authenticator apps:

  • Google Authenticator
  • Microsoft Authenticator
  • Authy (with cloud backup)
  • 1Password (integrated with password manager)
  • Hardware tokens (YubiKey, etc.)

QR Code Display:

1. Generate QR code at appropriate resolution (300x300px minimum)
2. Display QR code only over HTTPS
3. Include manual entry option for accessibility
4. Clear QR code from DOM after successful setup
5. Never store QR code images on server

User Experience:

1. Provide clear setup instructions with screenshots
2. Test code verification immediately after setup
3. Display recovery codes prominently before completing setup
4. Require user acknowledgment of recovery code storage
5. Provide "Use recovery code" option on login screen
6. Allow TOTP reset with proper identity verification

Testing and Validation

Unit Tests:

1. Test code generation with known secrets and timestamps
2. Verify time window acceptance (±1 step)
3. Test Base32 encoding and decoding
4. Validate QR code URI generation
5. Test rate limiting logic
6. Verify recovery code generation and validation

Integration Tests:

1. Test complete registration flow
2. Test complete authentication flow
3. Test recovery code usage
4. Test TOTP reset process
5. Test account lockout scenarios
6. Test concurrent authentication attempts

Security Testing:

1. Attempt brute-force attacks against rate limiting
2. Test timing attack resistance
3. Verify secret encryption at rest
4. Test TLS configuration
5. Attempt replay attacks with expired codes
6. Test recovery code single-use enforcement

Common Use Cases

User Registration with Mandatory TOTP

Many high-security applications require TOTP setup as part of the registration process.

Registration Flow:

  1. User provides email address
  2. System sends OTP to email for verification
  3. User verifies email ownership with OTP
  4. User sets password
  5. System generates and displays recovery codes
  6. User acknowledges saving recovery codes
  7. System generates TOTP secret and displays QR code
  8. User scans QR code in authenticator app
  9. User enters generated code to verify setup
  10. Registration completes with TOTP active

Benefits:

  • Ensures all accounts have MFA from day one
  • Establishes secure communication channel via email
  • Provides recovery mechanism before TOTP activation
  • Verifies TOTP works before account activation

Optional TOTP for Existing Accounts

Applications may allow existing users to optionally enable TOTP for enhanced security.

Enablement Flow:

  1. User navigates to security settings
  2. User selects "Enable two-factor authentication"
  3. System requires password re-authentication
  4. System generates TOTP secret and displays QR code
  5. User scans QR code and enters verification code
  6. System generates recovery codes
  7. User acknowledges saving recovery codes
  8. TOTP activation confirmed

Considerations:

  • Provide clear communication about security benefits
  • Never force sudden TOTP requirement without warning
  • Allow grace period for users to set up TOTP
  • Offer assistance for users unfamiliar with authenticator apps

Enterprise SSO with TOTP Step-Up

Organizations may use TOTP as a step-up authentication requirement for sensitive operations.

Step-Up Flow:

  1. User authenticates with SSO (SAML, OAuth, etc.)
  2. User accesses sensitive resource or performs privileged action
  3. System requires TOTP verification as step-up authentication
  4. User provides TOTP code
  5. System grants time-limited elevated access
  6. Elevated session expires after inactivity

Use Cases:

  • Accessing financial data
  • Approving high-value transactions
  • Modifying security settings
  • Administrative operations
  • Sensitive data exports

Mobile Application Authentication

Native mobile applications can implement TOTP authentication with enhanced user experience.

Mobile Considerations:

  • Support biometric unlock for stored TOTP secrets
  • Implement automatic code copying from authenticator apps
  • Use deep linking to open authenticator apps directly
  • Support push notification authentication as alternative
  • Handle backgrounding and session resumption gracefully
  • Implement secure storage for authentication state

TOTP vs. Other MFA Methods

TOTP vs. SMS-Based OTP

TOTP Advantages:

  • Works offline without cellular coverage
  • Not vulnerable to SIM swapping attacks
  • No dependency on carrier infrastructure
  • No per-message costs
  • More resistant to interception

SMS Advantages:

  • No app installation required
  • Works on any mobile phone
  • More familiar to non-technical users
  • Easier account recovery process

Recommendation: Use TOTP for security-critical applications; SMS OTP is acceptable for lower-risk scenarios but should not be considered strong MFA.

TOTP vs. Email-Based OTP

TOTP Advantages:

  • Faster authentication (no waiting for email delivery)
  • Works offline
  • Not vulnerable to email account compromise
  • Lower infrastructure costs

Email OTP Advantages:

  • No app installation required
  • Works on any device with email access
  • Easier for non-technical users
  • Can include contextual information in email

Recommendation: Email OTP is suitable as a first factor (passwordless authentication). TOTP provides stronger security as a second factor.

TOTP vs. Push Notification Authentication

TOTP Advantages:

  • Works without internet connectivity
  • No server-side push infrastructure required
  • Device-local code generation
  • Compatible with more devices

Push Notification Advantages:

  • Superior user experience (tap to approve)
  • Can display contextual authentication details
  • Harder to phish (no code to steal)
  • Can implement number matching for additional security

Recommendation: Push notifications provide better UX but require more infrastructure. TOTP is more universally compatible and works offline.

TOTP vs. Hardware Security Keys

TOTP Advantages:

  • Lower cost (uses existing smartphone)
  • Multiple accounts on one device
  • Easier backup and recovery
  • No physical token to carry

Hardware Key Advantages:

  • Phishing-resistant (cryptographic challenge-response)
  • Cannot be cloned or extracted
  • No battery required
  • Works without smartphone

Recommendation: Hardware keys provide the strongest security (FIDO2/WebAuthn). TOTP is an excellent balance of security and usability for most applications.

Compliance and Standards

RFC 6238 Compliance

Production TOTP implementations should fully comply with RFC 6238:

Required Parameters:

  • Time step: 30 seconds (default)
  • HMAC algorithm: SHA1 (minimum), SHA256/SHA512 (optional)
  • Code digits: 6 (minimum), 8 (recommended for high security)
  • Shared secret: 160 bits minimum (20 bytes)

Implementation Notes:

  • Must use Unix timestamp divided by time step
  • Must implement dynamic truncation as specified
  • Must handle time window tolerance
  • Should support algorithm agility (SHA256/SHA512)

Security Standards

NIST SP 800-63B Guidance:

  • TOTP qualifies as "something you have" authenticator
  • Approved for Authenticator Assurance Level 2 (AAL2)
  • Requires secure channel for secret provisioning
  • Recommends rate limiting and account lockout
  • Requires encrypted storage of shared secrets

PCI DSS Compliance:

  • TOTP satisfies MFA requirements for cardholder data access
  • Must implement proper key management
  • Must enforce separation of duties
  • Must log and monitor authentication events
  • Must protect against brute-force attacks

SOC 2 Considerations:

  • Document TOTP implementation in security policies
  • Implement proper access controls and audit logging
  • Ensure availability of authentication services
  • Maintain confidentiality of shared secrets
  • Regularly test MFA effectiveness

Troubleshooting Common Issues

Clock Skew Problems

Symptoms: Valid codes consistently rejected, user frustration

Solutions:

  • Implement ±1 time step tolerance (90-second window)
  • Track successful authentication time windows
  • Detect and compensate for consistent device clock drift
  • Provide "Sync time" option in authenticator apps
  • Document time synchronization requirements

Lost Authenticator Device

Symptoms: User cannot access account, lost phone/device

Solutions:

  • Provide recovery code option prominently on login screen
  • Implement identity verification for TOTP reset
  • Support multiple authenticator devices per account
  • Offer backup authentication methods (email OTP, SMS)
  • Provide clear account recovery documentation

QR Code Scanning Issues

Symptoms: Users cannot scan QR code, poor camera quality

Solutions:

  • Provide manual entry option with Base32 key
  • Ensure adequate QR code size (300x300px minimum)
  • Test QR codes with multiple authenticator apps
  • Provide good lighting instructions
  • Support alternative setup methods (deep links, NFC)

Verification Code Failures

Symptoms: User enters code but authentication fails

Common Causes:

  • User entering expired code (>90 seconds old)
  • Time synchronization issues
  • User entering code from wrong account
  • Copy-paste errors with whitespace
  • Rate limiting after multiple failures

Solutions:

  • Display time remaining on code in authenticator app
  • Implement graceful error messages
  • Allow re-entering codes without full re-authentication
  • Strip whitespace from user input
  • Provide "code expired" specific error message

Future Considerations

Algorithm Migration

While SHA1 is currently standard for TOTP, the industry is gradually moving toward stronger hash algorithms.

Migration Path:

  1. Implement support for SHA256 and SHA512 alongside SHA1
  2. Use algorithm parameter in otpauth:// URI
  3. Generate new secrets with SHA256 by default
  4. Maintain backward compatibility with existing SHA1 secrets
  5. Gradually deprecate SHA1 for new accounts
  6. Provide migration path for existing users

Passwordless Authentication with TOTP

TOTP can serve as the second factor in passwordless authentication flows.

Passwordless + TOTP Flow:

  1. User enters email address
  2. System sends OTP to email (first factor)
  3. User verifies email OTP
  4. System requires TOTP code (second factor)
  5. User provides TOTP code
  6. Authentication completes

This approach combines "something you have access to" (email) with "something you have" (authenticator device) for strong passwordless MFA.

WebAuthn Integration

Modern applications may offer both TOTP and WebAuthn (FIDO2) for maximum flexibility.

Dual Support Benefits:

  • Users choose their preferred method
  • Hardware key users get phishing-resistant authentication
  • TOTP users get broad device compatibility
  • Graceful degradation when hardware keys unavailable
  • Migration path from TOTP to WebAuthn

Implementation:

  • Allow users to register multiple authenticator types
  • Present authentication method selection at login
  • Support step-up authentication with strongest available method
  • Encourage WebAuthn adoption while maintaining TOTP support

TOTP authentication provides a proven, standardized approach to multi-factor authentication that balances strong security with practical usability. By requiring physical device possession in addition to primary credentials, TOTP significantly reduces the risk of account compromise from password-related attacks.

Successful TOTP implementation requires attention to several key areas: secure secret generation and storage, proper time window handling, comprehensive recovery mechanisms, and thoughtful user experience design. Following RFC 6238 standards and security best practices ensures interoperability with standard authenticator apps while maintaining strong security postures.

While newer authentication methods like WebAuthn offer advantages in specific scenarios, TOTP remains highly relevant due to its broad compatibility, offline functionality, and proven security track record. Organizations should consider TOTP as a core component of their authentication strategy, either as a standalone MFA solution or as part of a broader authentication framework supporting multiple factors and methods.

Additional Resources