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

Android Developer

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.

The founder's survey report on "What Matters For Startup" is released - Get your copy and learn the trends of successful companies :)

Download Free eBook Now!

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

"Mindbowser was very helpful with explaining the development process and started quickly on the project."

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

"The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs."

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

"They're very tech-savvy, yet humble."

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

"Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier"

author
Katie Taylor
Founder, Child Life On Call
coma

“As a founder of a budding start up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity."

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give