Firebase Authentication with Phone Number OTP in Android

Firebase Authentication with Phone Number OTP in Android

Firebase Authentication provides a seamless user authentication experience without the need to manage server-side infrastructure. Phone authentication via OTP (One-Time Password) is one of the methods supported by Firebase.

Here's a step-by-step guide to implement Firebase Phone Authentication with OTP:

1. Setup Firebase Project

  • Create a Firebase project on the Firebase Console.
  • Add an Android app to your Firebase project and download the google-services.json file.
  • Place this file in your app's app directory in Android Studio.

2. Add Dependencies

Add the Firebase Authentication SDK to your build.gradle (Module: app):

implementation 'com.google.firebase:firebase-auth:19.2.0' 

Ensure you also have the Google services plugin applied at the bottom of your build.gradle:

apply plugin: 'com.google.gms.google-services' 

3. Initialize Firebase

In your main activity or application class, initialize Firebase:

FirebaseApp.initializeApp(this); 

4. Start Phone Authentication

FirebaseAuth auth = FirebaseAuth.getInstance(); PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(@NonNull PhoneAuthCredential credential) { signInWithPhoneAuthCredential(credential); } @Override public void onVerificationFailed(@NonNull FirebaseException e) { // Handle the error, for instance, display a message to the user } @Override public void onCodeSent(@NonNull String verificationId, @NonNull PhoneAuthProvider.ForceResendingToken token) { // Save the verificationId and resending token to use later // Prompt the user to enter the code } }; PhoneAuthProvider.getInstance().verifyPhoneNumber( phoneNumber, // Phone number to verify 60, // Timeout duration TimeUnit.SECONDS, // Unit of the timeout this, // Activity (for callback binding) mCallbacks); // OnVerificationStateChangedCallbacks 

5. Verify the Code

Once the user has received the OTP and entered it in your app, you can validate it:

PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code); signInWithPhoneAuthCredential(credential); 

6. Sign in

Use the following method to authenticate the user:

private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) { auth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success FirebaseUser user = task.getResult().getUser(); // Update UI or navigate to the main activity } else { // Sign in failed, display a message and update the UI } } }); } 

7. Handling Errors

Handle any errors during the process, such as invalid codes or expired OTPs, by checking the task.getException() method in the onComplete callback.

8. Enable Phone Number sign-in for your Firebase project

  • In the Firebase console, open the Authentication section.
  • On the Sign-in Method page, enable the Phone Number sign-in method.

Remember to also consider edge cases, such as when the user doesn't receive an OTP, allowing them to request another OTP after a reasonable duration.

This is a basic guide. For a production application, you'd also want to handle edge cases, offer more feedback to the user, and ensure a seamless experience across the authentication process.

Examples

  1. Implementing OTP verification with Firebase in Android:

    • Description: This example demonstrates how to implement OTP (One-Time Password) verification using Firebase Authentication.
    • Code:
      PhoneAuthProvider.getInstance().verifyPhoneNumber( phoneNumber, // Phone number to verify 60, // Timeout duration TimeUnit.SECONDS, // Unit of timeout this, // Activity (context) callbacks); // Callbacks for verification 
  2. Phone Number Authentication with Firebase example code:

    • Description: Shows how to authenticate users using their phone numbers with Firebase Authentication.
    • Code:
      FirebaseAuth auth = FirebaseAuth.getInstance(); auth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // User is signed in } else { // Authentication failed } } }); 
  3. Handling Firebase Phone Authentication callbacks in Android:

    • Description: Illustrates how to handle callbacks from Firebase during the phone authentication process.
    • Code:
      PhoneAuthProvider.OnVerificationStateChangedCallbacks callbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential credential) { // Auto-retrieval or instant verification } @Override public void onVerificationFailed(FirebaseException e) { // Verification failed } // Other callback methods }; 
  4. Handling errors and edge cases in Firebase Phone Authentication:

    • Description: Covers how to handle errors and edge cases that may occur during the Firebase Phone Authentication process.
    • Code:
      task.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Handle failure } }); 

More Tags

hp-uft client-certificates notifications visualization iso web-testing tedious google-maps-api-3 compilation multipart

More Programming Guides

Other Guides

More Programming Examples