Add TOTP multi-factor authentication to your Android app  |  Firebase Authentication (2024)

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 youenable this feature, users attempting to sign in to your app see a request for aTOTP. To generate it, they must use an authenticator app capable of generatingvalid TOTP codes, such as Google Authenticator.

Before you begin

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

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

  3. If you haven't done so already, install theFirebase Android SDK.

    TOTP MFA is only supported on theAndroid SDK version v22.1.0and above.

Enable TOTP MFA

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

To use the Admin SDK, do the following:

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

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

  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 adjacenttime-window intervals from which to accept TOTPs, from zero to ten. Thedefault is five.

      TOTPs work by ensuring that when two parties (the prover and thevalidator) generate OTPs within the same time window (typically 30 secondslong), they generate the same password. However, to accommodate clockdrift between parties and human response time, you can configure the TOTPservice 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-windowintervals, from zero to ten. The default is five.

    TOTPs work by ensuring that when two parties (the prover and thevalidator) generate OTPs within the same time window (typically 30 secondslong), they generate the same password. However, to accommodate clockdrift between parties and human response time, you can configure the TOTPservice to also accept TOTPs from adjacent windows.

Choose an enrollment pattern

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

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

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

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

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

Enroll users in TOTP MFA

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

  1. Re-authenticate the user.

  2. Generate a TOTP secret for the authenticated user:

    // Generate a TOTP secret.Firebase.auth.currentUser.multiFactor.session .addOnSuccessListener { multiFactorSession -> TotpMultiFactorGenerator.generateSecret(multiFactorSession) .addOnSuccessListener { totpSecret -> // 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 theirauthenticator app:

    // Display this key:val secret = totpSecret.sharedSecretKey

    In addition to displaying the secret key, you can attempt to automaticallyadd it to the device's default authenticator app. To do so, generate aGoogle Authenticator-compatible key URI,and pass it to openInOtpApp():

    val qrCodeUri = totpSecret.generateQrCodeUrl( currentUser.email ?: "default account", "Your App Name")totpSecret.openInOtpApp(qrCodeUri)

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

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

    // Ask the user for a verification code from the authenticator app.val verificationCode = // Code from user input.// Finalize the enrollment.val multiFactorAssertion = TotpMultiFactorGenerator .getAssertionForEnrollment(totpSecret, verificationCode)Firebase.auth.currentUser.multiFactor.enroll(multiFactorAssertion, "TOTP") .addOnSuccessListener { // Enrollment complete. }

Sign in users with a second factor

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

  1. Call one of the signInWith- methods as you would if you weren't using MFA.(For example, signInWithEmailAndPassword().) If the method throws anFirebaseAuthMultiFactorException, start your app's MFA flow.

    Firebase.auth.signInWithEmailAndPassword(email, password) .addOnSuccessListener { result -> // 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.) // ... } .addOnFailureListener { exception -> when (exception) { is FirebaseAuthMultiFactorException -> { // Initiate your second factor sign-in flow. (See next step.) // ... } } }
  2. Your app's MFA flow should first prompt the user to choose the second factorthey want to use. You can get a list of supported second factors byexamining the hints property of a MultiFactorResolver instance:

    val enrolledFactors = exception.resolver.hints.map { it.displayName }
  3. If the user chooses to use TOTP, prompt them to type the TOTP displayed ontheir authenticator app and use it to sign in:

    when (exception.resolver.hints[selectedIndex].factorId) { TotpMultiFactorGenerator.FACTOR_ID -> { val otpFromAuthenticator = // OTP typed by the user. val assertion = TotpMultiFactorGenerator.getAssertionForSignIn( exception.resolver.hints[selectedIndex].uid, otpFromAuthenticator ) exception.resolver.resolveSignIn(assertion) .addOnSuccessListener { result -> // Successfully signed in! } .addOnFailureListener { resolveError -> // Invalid or expired OTP. } } PhoneMultiFactorGenerator.FACTOR_ID -> { // Handle SMS second factor. }}

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 unenrollfrom the most recently enabled option, they receive an auth/user-token-expiredand are logged out. The user must sign in again and verify theirexisting credentials—for example, an email address and password.

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

Firebase.auth.currentUser.multiFactor.unenroll(mfaEnrollmentId) .addOnSuccessListener { // Second factor unenrolled. } .addOnFailureListener { exception -> when (exception) { is FirebaseAuthInvalidUserException -> { // Second factor unenrolled. If the user was signed out, re-authenticate // them. // For example, if they signed in with a password, prompt them to // provide it again, then call `reauthenticateWithCredential()` as shown // below. val credential = EmailAuthProvider.getCredential(email, password) currentUser.reauthenticate(credential) .addOnSuccessListener {  // Success! } .addOnFailureListener {  // Bad email address and password combination. } } } }

What's next

  • Manage multi-factor usersprogrammatically with the Admin SDK.
Add TOTP multi-factor authentication to your Android app  |  Firebase Authentication (2024)

FAQs

How do I add multi-factor authentication to my Android app? ›

Go to the Identity Platform MFA page in the Google Cloud console. In Multi-Factor Authentication, click Enable. Enter the phone numbers you'll be testing your app with. While optional, registering test phone numbers is strongly recommended to avoid throttling during development.

How do I enable multi-factor authentication using TOTP? ›

Enable TOTP MFA for your app
  1. Before you begin. Enable at least one provider that supports MFA. ...
  2. Enable TOTP MFA at the project level. ...
  3. Enable TOTP MFA at the tenant level. ...
  4. Choose an enrollment pattern. ...
  5. Enroll users in TOTP MFA. ...
  6. Sign in users with a second factor. ...
  7. Unenroll from TOTP MFA. ...
  8. What's next.

How do I set up TOTP on Google Authenticator? ›

To register a mobile device for use with the TOTP tool:
  1. On your mobile device, open the Google Authenticator app.
  2. Select Settings > Add an account.
  3. Use either of the following methods to configure the account: Scan a barcode: Select Scan a barcode. ...
  4. Specify a unique name for the account.
  5. Tap Done.

How do I add authenticator to my Android? ›

Set up Google Authenticator for your Google Account
  1. On your Android device, go to your 2-Step Verification settings for your Google Account. You may need to sign in.
  2. Tap Set up authenticator. On some devices, tap Get Started.
  3. Follow the on-screen steps.

How do I enable multi-factor authentication? ›

Turn on MFA for each account or app!
  1. Go to Settings. It may be called Account Settings, Settings & Privacy or similar.
  2. Look for and turn on MFA. It may be called two-factor authentication, two-step authentication or similar.
  3. Confirm. Select which MFA method to use from the options provided by each account or app.

How do I set up an MFA app? ›

  1. Step 1 - sign into Office 365 on your computer or laptop. ...
  2. Step 2 - installing the authenticator app on your mobile phone. ...
  3. Step 3 - return to your personal or.
  4. Step 4 - using your mobile.
  5. Step 5 - testing the authentication is working on your computer.

Is TOTP the same as 2FA? ›

TOTP stands for Time-based One-Time Passwords and is a common form of two-factor authentication (2FA). Unique numeric passwords are generated with a standardized algorithm that uses the current time as an input.

Is Google Authenticator a TOTP app? ›

Google Authenticator is a software-based authenticator by Google. It implements multi-factor authentication services using the time-based one-time password (TOTP; specified in RFC 6238) and HMAC-based one-time password (HOTP; specified in RFC 4226), for authenticating users of software applications.

How do I get TOTP? ›

How can I create and Aadhar TOTP
  1. Download the mAadhaar app on your smartphone.
  2. Log in using your Aadhaar details.
  3. Tap on 'MY AADHAAR' and select 'GET TOTP'
  4. An 8-digit TOTP code will appear, valid for 30 seconds.
Feb 17, 2024

Does Android have a built in authenticator? ›

If your phone is eligible, Google will automatically use your phone's built-in security key for additional protection when you sign in to new devices. Important: You can only have one built-in security key on your account. If you have more than one eligible phone, you'll need to choose one.

How do I manually add authenticator? ›

Open Authenticator on your phone and select the plus icon and select Add account. Select Work or school account then tap Scan a QR Code. Notes: If you can't use your camera to scan a QR Code, click Can't scan the image on your PC and tap Enter code manually on your mobile.

How to enable multi-factor authentication on a Google Account? ›

Turn on 2-Step Verification
  1. Open your Google Account.
  2. In the navigation panel, select Security.
  3. Under “How you sign in to Google,” select 2-Step Verification. Get started.
  4. Follow the on-screen steps.

How do I download multi-factor authentication app? ›

If you use an Android phone, go to the Google Play store and install the Microsoft Authenticator app. If you use an iPhone, use the Apple store to download the app.

How do I add authentication to app Service? ›

In Resource groups, find and select your resource group. In Overview, select your app's management page. On your app's left menu, select Authentication, and then select Add identity provider.

How do I enable multi user mode on Android? ›

Add or update users
  1. Open your device's Settings app.
  2. Tap System. Multiple users. If you can't find this setting, try searching your Settings app for users .
  3. Tap Add user. OK. If you don't find "Add user," tap Add user or profile User. OK. ...
  4. Enter a name for the new user.

How do I set up multi-factor authentication on ID me app? ›

Sign in with code generator
  1. Sign in to your ID.me account.
  2. Select Code Generator for MFA.
  3. When you are prompted to enter your six-digit code, open your ID.me Authenticator app and enter the code that displays. A new code is generated every 30 seconds. Enter your code before the timer reaches zero.

Top Articles
Persuade Definition & Meaning | Britannica Dictionary
What should you do if you suspect credit card fraud?
Frases para un bendecido domingo: llena tu día con palabras de gratitud y esperanza - Blogfrases
Mcgeorge Academic Calendar
Eric Rohan Justin Obituary
Concacaf Wiki
Craigslist Estate Sales Tucson
Santa Clara Valley Medical Center Medical Records
Mycarolinas Login
Saberhealth Time Track
Conan Exiles Thrall Master Build: Best Attributes, Armor, Skills, More
Cinebarre Drink Menu
Lake Nockamixon Fishing Report
Craftology East Peoria Il
Aucklanders brace for gales, hail, cold temperatures, possible blackouts; snow falls in Chch
Arre St Wv Srj
Find Such That The Following Matrix Is Singular.
Spectrum Field Tech Salary
Harem In Another World F95
Toy Story 3 Animation Screencaps
91 East Freeway Accident Today 2022
Joann Ally Employee Portal
Huntersville Town Billboards
Allybearloves
Adt Residential Sales Representative Salary
Www.craigslist.com Savannah Ga
Egizi Funeral Home Turnersville Nj
Greensboro sit-in (1960) | History, Summary, Impact, & Facts
Meridian Owners Forum
Amelia Chase Bank Murder
Hesburgh Library Catalog
Abga Gestation Calculator
Warn Notice Va
Mobile Maher Terminal
Leland Nc Craigslist
LEGO Star Wars: Rebuild the Galaxy Review - Latest Animated Special Brings Loads of Fun With An Emotional Twist
Solve 100000div3= | Microsoft Math Solver
Tra.mypatients Folio
Atlantic Broadband Email Login Pronto
Carespot Ocoee Photos
October 31St Weather
Umiami Sorority Rankings
Hindilinks4U Bollywood Action Movies
Conan Exiles Armor Flexibility Kit
Fedex Passport Locations Near Me
BCLJ July 19 2019 HTML Shawn Day Andrea Day Butler Pa Divorce
N33.Ultipro
CPM Homework Help
Product Test Drive: Garnier BB Cream vs. Garnier BB Cream For Combo/Oily Skin
Best brow shaping and sculpting specialists near me in Toronto | Fresha
Inloggen bij AH Sam - E-Overheid
Kindlerso
Latest Posts
Article information

Author: Otha Schamberger

Last Updated:

Views: 6345

Rating: 4.4 / 5 (75 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Otha Schamberger

Birthday: 1999-08-15

Address: Suite 490 606 Hammes Ferry, Carterhaven, IL 62290

Phone: +8557035444877

Job: Forward IT Agent

Hobby: Fishing, Flying, Jewelry making, Digital arts, Sand art, Parkour, tabletop games

Introduction: My name is Otha Schamberger, I am a vast, good, healthy, cheerful, energetic, gorgeous, magnificent person who loves writing and wants to share my knowledge and understanding with you.