Add TOTP multi-factor authentication to your iOS app

If you've upgraded to Firebase Authentication with Identity Platform, you can add time-based one-time password (TOTP) multi-factor authentication (MFA) to your app.

Firebase Authentication with Identity Platform lets you use a TOTP as an additional factor for MFA. When you enable this feature, users attempting to sign in to your app see a request for a TOTP. To generate it, they must use an authenticator app capable of generating valid TOTP codes, such as Google Authenticator.

Before you begin

  1. Enable at least one provider that supports MFA. Note that all providers except the following support MFA:

    • Phone auth
    • Anonymous auth
    • Custom auth tokens
    • Apple Game Center
  2. Ensure your app verifies user email addresses. MFA requires email verification. This prevents malicious actors from registering for a service with an email address that they don't own, and then locking out the actual owner of the email address by adding a second factor.

  3. If you haven't done so already, install the Firebase Apple SDK.

    TOTP MFA is only supported on the Apple SDK version v10.12.0 and above, and only on iOS.

Enable TOTP MFA

To enable TOTP as a second factor, use the Admin SDK or call the project configuration REST endpoint.

To use the Admin SDK, do the following:

  1. If you haven't done so already, install the Firebase Admin Node.js SDK.

    TOTP MFA is only supported on Firebase Admin Node.js SDK versions 11.6.0 and above.

  2. Run the following:

    import { getAuth } from 'firebase-admin/auth';
    
    getAuth().projectConfigManager().updateProjectConfig(
    {
          multiFactorConfig: {
              providerConfigs: [{
                  state: "ENABLED",
                  totpProviderConfig: {
                      adjacentIntervals: NUM_ADJ_INTERVALS
                  }
              }]
          }
    })
    

    Replace the following:

    • NUM_ADJ_INTERVALS: The number of adjacent time-window intervals from which to accept TOTPs, from zero to ten. The default is five.

      TOTPs work by ensuring that when two parties (the prover and the validator) generate OTPs within the same time window (typically 30 seconds long), they generate the same password. However, to accommodate clock drift between parties and human response time, you can configure the TOTP service to also accept TOTPs from adjacent windows.

To enable TOTP MFA using the REST API, run the following:

curl -X PATCH "https://identitytoolkit.googleapis.com/admin/v2/projects/PROJECT_ID/config?updateMask=mfa" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    -H "X-Goog-User-Project: PROJECT_ID" \
    -d \
    '{
        "mfa": {
          "providerConfigs": [{
            "state": "ENABLED",
            "totpProviderConfig": {
              "adjacentIntervals": NUM_ADJ_INTERVALS
            }
          }]
       }
    }'

Replace the following:

  • PROJECT_ID: The project ID.
  • NUM_ADJ_INTERVALS: The number of time-window intervals, from zero to ten. The default is five.

    TOTPs work by ensuring that when two parties (the prover and the validator) generate OTPs within the same time window (typically 30 seconds long), they generate the same password. However, to accommodate clock drift between parties and human response time, you can configure the TOTP service to also accept TOTPs from adjacent windows.

Choose an enrollment pattern

You can choose whether your app requires multi-factor authentication, and how and when to enroll your users. Some common patterns include the following:

  • Enroll the user's second factor as part of registration. Use this method if your app requires multi-factor authentication for all users.

  • Offer a skippable option to enroll a second factor during registration. If you want to encourage but not require multi-factor authentication in your app, you might use this approach.

  • Provide the ability to add a second factor from the user's account or profile management page, instead of the sign-up screen. This minimizes friction during the registration process, while still making multi-factor authentication available for security-sensitive users.

  • Require adding a second factor incrementally when the user wants to access features with increased security requirements.

Enroll users in TOTP MFA

After you enable TOTP MFA as a second factor for your app, implement client-side logic to enroll users in TOTP MFA:

  1. Re-authenticate the user.

  2. Generate a TOTP secret for the authenticated user:

    // Generate a TOTP secret.
    guard let mfaSession = try? await currentUser.multiFactor.session() else { return }
    guard let totpSecret = try? await TOTPMultiFactorGenerator.generateSecret(with: mfaSession) else { return }
    
    // Display the secret to the user and prompt them to enter it into their
    // authenticator app. (See the next step.)
    
  3. Display the secret to the user and prompt them to enter it into their authenticator app:

    // Display this key:
    let secret = totpSecret.sharedSecretKey()
    

    In addition to displaying the secret key, you can attempt to automatically add it to the device's default authenticator app. To do so, generate a Google Authenticator-compatible key URI, and pass it to openInOTPApp(withQRCodeURL:):

    let otpAuthUri = totpSecret.generateQRCodeURL(
        withAccountName: currentUser.email ?? "default account",
        issuer: "Your App Name")
    totpSecret.openInOTPApp(withQRCodeURL: otpAuthUri)
    

    After the user adds their secret to their authenticator app, it will start generating TOTPs.

  4. Prompt the user to type the TOTP displayed by their authenticator app and use it to finalize MFA enrollment:

    // Ask the user for a verification code from the authenticator app.
    let verificationCode = // Code from user input.
    
    // Finalize the enrollment.
    let multiFactorAssertion = TOTPMultiFactorGenerator.assertionForEnrollment(
        with: totpSecret,
        oneTimePassword: verificationCode)
    do {
        try await currentUser.multiFactor.enroll(
            with: multiFactorAssertion,
            displayName: "TOTP")
    } catch {
        // Wrong or expired OTP. Re-prompt the user.
    }
    

Sign in users with a second factor

To sign in users with TOTP MFA, use the following code:

  1. Call one of the signIn(with...:)- methods as you would if you weren't using MFA (for example, signIn(withEmail:password:)). If the method throws an error with the code secondFactorRequired, start your app's MFA flow.

    do {
        let authResult = try await Auth.auth().signIn(withEmail: email, password: password)
    
        // If the user is not enrolled with a second factor and provided valid
        // credentials, sign-in succeeds.
    
        // (If your app requires MFA, this could be considered an error
        // condition, which you would resolve by forcing the user to enroll a
        // second factor.)
    
        // ...
    } catch let error as AuthErrorCode where error.code == .secondFactorRequired {
        // Initiate your second factor sign-in flow. (See next step.)
        // ...
    } catch {
        // Other auth error.
        throw error
    }
    
  2. Your app's MFA flow should first prompt the user to choose the second factor they want to use. You can get a list of supported second factors by examining the hints property of a MultiFactorResolver instance:

    let mfaKey = AuthErrorUserInfoMultiFactorResolverKey
    guard let resolver = error.userInfo[mfaKey] as? MultiFactorResolver else { return }
    let enrolledFactors = resolver.hints.map(\.displayName)
    
  3. If the user chooses to use TOTP, prompt them to type the TOTP displayed on their authenticator app and use it to sign in:

    let multiFactorInfo = resolver.hints[selectedIndex]
    switch multiFactorInfo.factorID {
    case TOTPMultiFactorID:
        let otpFromAuthenticator = // OTP typed by the user.
        let assertion = TOTPMultiFactorGenerator.assertionForSignIn(
            withEnrollmentID: multiFactorInfo.uid,
            oneTimePassword: otpFromAuthenticator)
        do {
            let authResult = try await resolver.resolveSignIn(with: assertion)
        } catch {
            // Wrong or expired OTP. Re-prompt the user.
        }
    default:
        return
    }
    

Unenroll from TOTP MFA

This section describes how to handle a user unenrolling from TOTP MFA.

If a user has signed up for multiple MFA options, and if they unenroll from the most recently enabled option, they receive an auth/user-token-expired and are logged out. The user must sign in again and verify their existing credentials—for example, an email address and password.

To unenroll the user, handle the error, and trigger reauthentication, use the following code:

guard let currentUser = Auth.auth().currentUser else { return }

// Prompt the user to select a factor to unenroll, from this array:
currentUser.multiFactor.enrolledFactors

// ...

// Unenroll the second factor.
let multiFactorInfo = currentUser.multiFactor.enrolledFactors[selectedIndex]
do {
    try await currentUser.multiFactor.unenroll(with: multiFactorInfo)
} catch let error as AuthErrorCode where error.code == .invalidUserToken {
    // Second factor unenrolled, but the user was signed out. Re-authenticate
    // them.
}

What's next