Configuring Time-based One-Time Password (TOTP) multi-factor authentication (MFA) in Firebase for Android apps enhances the security of user sign-ins by adding an extra layer of verification. This step-by-step guide will walk you through the process, leveraging Firebase’s built-in support for TOTP MFA.
Step 1: Update Your Firebase Admin SDK
Before proceeding, ensure that your Firebase project uses a compatible version of the Firebase Admin SDK. TOTP MFA is supported on Firebase Admin Node.js SDK versions 11.6.0 and above . If your project does not meet this requirement, update the SDK to a supported version.
You can install or upgrade the Firebase Admin SDK using npm:
npm install firebase-admin@latest
Once updated, initialize the Admin SDK in your backend environment with your Firebase project credentials.
Step 2: Enable TOTP MFA in Firebase
To enable TOTP MFA, you can either use the Firebase Admin SDK or call the project configuration REST endpoint. Using the Admin SDK is typically more straightforward for developers managing backend logic.
Here’s an example of enabling TOTP MFA using the Admin SDK:
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault(),
projectId: 'your-project-id',
});
const identityPlatformClient = admin.auth();
identityPlatformClient.setProjectConfig({
mfaConfig: {
state: 'ENABLED',
totpConfig: {
providerState: 'ENABLED',
},
},
})
.then(() => {
console.log('TOTP MFA enabled successfully.');
})
.catch((error) => {
console.error('Error enabling TOTP MFA:', error);
});
This code snippet enables TOTP MFA at the project level, allowing users to register and use TOTP authenticators during sign-in .
Step 3: Configure Your Android App
Now that TOTP MFA is enabled on the backend, it’s time to configure your Android app to support TOTP-based second-factor authentication.
Start by ensuring you have the latest Firebase Authentication dependencies in your build.gradle
file:
implementation 'com.google.firebase:firebase-auth:22.2.0'
Next, prompt users to enroll in TOTP MFA after they’ve signed in with their primary factor (e.g., email/password or phone number). Use the FirebaseAuth
instance to trigger the enrollment flow:
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
user.multiFactor().getSession()
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
MultiFactorSession session = task.getResult();
TotpMultiFactorGenerator totpGenerator = TotpMultiFactorGenerator.getNewInstance("YourAppName");
MultiFactorAssertion assertion = totpGenerator.generateSetupAssertion(session);
user.multiFactor().enroll(assertion, "TOTP Factor")
.addOnCompleteListener(enrollTask -> {
if (enrollTask.isSuccessful()) {
Log.d("TOTP", "Enrollment successful.");
} else {
Log.e("TOTP", "Enrollment failed.", enrollTask.getException());
}
});
}
});
}
This code generates a new TOTP secret and initiates the enrollment process. Users will need to scan the generated QR code with a TOTP-compatible authenticator app like Google Authenticator or Authy.
Step 4: Sign In with TOTP MFA
When a user signs in with their primary credentials, Firebase may prompt them to complete the second factor using TOTP. During this step, the user must enter the current one-time password generated by their authenticator app.
Use the following code to handle the second factor sign-in:
mAuth.signInWithEmailAndPassword(email, password)
.addOnFailureListener(e -> {
if (e instanceof FirebaseAuthMultiFactorException) {
FirebaseAuthMultiFactorException multiFactorException = (FirebaseAuthMultiFactorException) e;
MultiFactorResolver resolver = multiFactorException.getResolver();
MultiFactorSession session = resolver.getSession();
TotpMultiFactorGenerator totpGenerator = TotpMultiFactorGenerator.getNewInstance("YourAppName");
String totpCode = // Retrieve the TOTP code from user input
MultiFactorAssertion assertion = totpGenerator.generateSignInAssertion(totpCode, session);
resolver.resolveSignIn(assertion)
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Log.d("TOTP", "Sign-in successful with TOTP.");
} else {
Log.e("TOTP", "Failed to sign in with TOTP.", task.getException());
}
});
}
});
This ensures that users are prompted to provide their TOTP code when signing in, completing the two-factor authentication process.
Step 5: Test and Monitor
After implementing TOTP MFA, thoroughly test the flow in different scenarios—enrollment, sign-in, and reauthentication. Ensure that users receive clear instructions on how to set up and use their authenticator apps.
Additionally, monitor user feedback and usage patterns to identify any friction points in the authentication experience. Firebase Authentication logs and analytics can help you track success rates and detect potential issues .
Conclusion
Adding TOTP-based multi-factor authentication to your Android app via Firebase significantly improves account security without overly complicating the user experience. By following these steps, you can seamlessly integrate TOTP into your existing Firebase Authentication setup, offering users a modern and secure way to protect their accounts .