Firebase Authentication & Email Verification In Android

What is Firebase:

Firebase is a collection of tools and a complete solution for the backend, it handles Authentication, real-time database, cloud firestore, etc and many more features.

Here in short we will see what tools are present in the Firebase.

  • Build: Authentication, Cloud firestore, Real-time Database, Storage, Hosting, Functions, machine learning.
  • Release & Monitoring: Crashlytics, Performance, Test lab, App Distribution.
  • Analytics: Dashboard, Real-time, Events, Conversions, Audiences, Funnels, Custom definitions, Latest release, Retention, DebugView.
  • Engage: Predictions, A/B testing, Cloud messaging, In-App messaging, Remote config, Dynamic Links, AdMob,
  • Extensions

This blog will cover how to implement Firebase Authentication & Verification of a user using an email address.

Step 1:

The step is we need to create a new project in android studio, in AndroidStudio Go to File -> New -> New Project -> Choose an activity ( I am selecting empty activity you can choose as per your choice ) -> Give a name to project and choose a directory ( where we want to save the project and ) -> Click on finish.

Step 2:

Create a project on the Firebase console.

To register the project on Firebase follows the steps:

  1. Click on add project, after clicking you will redirect to create project tab.
  2. On the create project tab give the project name, and click on the continue button.
  3. Follow the steps and click on create the project.

Here we are done with the project creation on Firebase.

Now we need to add an application, here we will see how to add an android application to the Firebase project.

In our created Firebase project we will see symbols of iOS, Android, Web. So we will see how to register Android applications.

On clicking on the Android symbol, we will redirect to the “Add Firebase to your Android app” screen.

Need to follow 4 steps for registration of application.

  • Register app

    1. Add package name of android studio application.
    2. Add the nickname of the application.
    3. Add Debug signing certificate SHA-1.
    4. Click on the Register app.
  • Download Config file

    1. Download the google-services.json file
    2. Add into the app folder of the android studio project.
  • Add Firebase SDK into Android Studio project

  1. Project-level build.gradle
    buildscript {
    
      repositories {
    
        // Check that you have the following line (if not, add it):
    
        google()  // Google's Maven repository
    
      }
    
      dependencies {
    
        // Add this line
    
        classpath 'com.google.gms:google-services:4.3.8'
    
      }
    
    }
    
    allprojects {
    
      repositories {
    
        // Check that you have the following line (if not, add it):
    
        google()  // Google's Maven repository
    
        ...
    
      }
    
    }

2. App-level build.gradle

apply plugin: 'com.android.application'

// Add this line

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

dependencies {

  // Import the Firebase BoM

  implementation platform('com.google.Firebase:Firebase-bom:28.0.1')

  // Add the dependency for the Firebase SDK for Google Analytics

  // When using the BoM, don't specify versions in Firebase dependencies

  implementation 'com.google.Firebase:Firebase-analytics'

  // Add the dependencies for any other desired Firebase products

  // https://Firebase.google.com/docs/android/setup#available-libraries

}
  • Click on Continue to console

Here we are done with the registration process.

Now we have to enable the authentication function in the Firebase project.

After clicking on the enable button in the sign-in-method option choose the method which you want to use for Authentication. Let’s explore how to Authenticate users using email addresses.

So here I am enabling the email/password option for Authentication.

We can enable more than one authentication method as well.

So here we are done with our Firebase settings.

Let’s see the coding section…….

Step 3:

Create an instance of FirebaseAuth:

   public static final FirebaseAuth AUTH = FirebaseAuth.getInstance();

Create User using email and password:

protected final void createUserAuthWithEmailAndPassword(String emailId, String password) {

       AUTH.createUserWithEmailAndPassword(emailId, password).addOnCompleteListener((@NonNull Task<AuthResult> task) -> {

           if (task.isSuccessful())

             Toast.makeText(getApplicationContext(),”Success”,Toast.LENGHT_LONG).show();    

           else    Toast.makeText(getApplicationContext(),task.getException()).getMessage(),Toast.LENGHT_LONG).show();         

       });

   }

Sign in with Email and Password:

protected final void authSignInWithEmailAndPassword(String emailId, String password) {

       AUTH.signInWithEmailAndPassword(emailId, password).addOnCompleteListener((@NonNull Task<AuthResult> task) -> {

           if (task.isSuccessful())

             Toast.makeText(getApplicationContext(),”Success”,Toast.LENGHT_LONG).show();    

           else

Toast.makeText(getApplicationContext(),task.getException()).getMessage(),Toast.LENGHT_LONG).show();

       });

   }

Send verification email to a registered user:

To send verification emails to registered users we need to get a FirebaseUser instance.

public static final FirebaseUser AUTH_USER = FirebaseAuth.getInstance().getCurrentUser()!=null ? FirebaseAuth.getInstance().getCurrentUser(): null ;

Send verification email using the below method:

protected final void verifyEmailIdSentEmail( FirebaseUser FirebaseUser){

       FirebaseUser.sendEmailVerification()

               .addOnCompleteListener(new OnCompleteListener<Void>() {

                   @Override

                   public void onComplete(@NonNull Task<Void> task) {

                       if (task.isSuccessful()) {

                          Toast.makeText(getApplicationContext(),”Success”,Toast.LENGHT_LONG).show(); 

                       }

                       else

                       {                                                  Toast.makeText(getApplicationContext(),”Failed”,Toast.LENGHT_LONG).show(); 

                       }

                   }

               }).addOnCanceledListener(new OnCanceledListener() {

           @Override

           public void onCanceled() {

Toast.makeText(getApplicationContext(),task.getException()).getMessage(),Toast.LENGHT_LONG).show();

           }

       });

   }

We can check if user is verified or not:

public static boolean  checkIfEmailVerified(FirebaseUser FirebaseUser)

   {

       if (FirebaseUser != null) {

           return FirebaseUser.isEmailVerified();

       }

       return false;

   }

To reset the password we can send an email to registered email address

protected final void resetPassword(String emailId,final CallBack callback){

       AUTH.sendPasswordResetEmail(emailId)

               .addOnCompleteListener(new OnCompleteListener() {

                   @Override

                   public void onComplete(@NonNull Task task) {

                       if (task.isSuccessful()) {

                           Toast.makeText(getApplicationContext(),”Success”,Toast.LENGHT_LONG).show();

                       } else {

                    Toast.makeText(getApplicationContext(),,task.getException()).getMessage(),Toast.LENGHT_LONG).show();

                       }

                   }

               });

   }

To SignOut we can use Firebase signOut function like below:

protected final void authSignOut(final CallBack callback) {

       FirebaseAuth.AuthStateListener authStateListener = FirebaseAuth -> {

           if (AUTH.getCurrentUser() == null) {

               callback.onSuccess(FirebaseAuth);

           }

       };

       AUTH.addAuthStateListener(authStateListener);

       AUTH.signOut();

   }

Like this so many features are available in Firebase we can do many more things using Firebase.

Hope it will be helpful to you!!!😊

Priyanka M

Senior Software Engineer

Priyanka is an android developer with around 3.5 years of experience developing Android applications with core functionality. She has in-depth knowledge of Java and React Native. Priyanka likes to learn new things and share.

Keep Reading

Keep Reading

Let's get in touch!