Image Source https://blog.scalefusion.com/wp-content/uploads/2FA-fb@2x-768×497.png

Here is the GitHub – android-2step authentication-Firebase link for this project.

Introduction

Firebase authentication adds one layer of security while Android two-step authentication henceforth will add an extra layer of security to your application. In this blog, we are going to follow a step by step tutorial on how to create an android two-step authentication signup system using Firebase and as a result, it will add a second layer of authentication”two-factor authentication (2FA)”.


Firebase is Google’s mobile platform that helps you quickly develop high-quality apps because it provides a real-time database and backend as a service and in the two-step authentication signup system we will use Firebase services such as Firebase real-time database and Firebase authentication.

What motivated me in doing this project “android two-step authentication signup system using Firebase” is because security is the key thing in each and every application more so allowing a two-step authentication will add another layer of security before a user manages to access the application. In Addition, Android technology is on the rise such that each and every person finds it easy to own, hence most of the system is shifting to having an android application, and applying this two-step authentication for users will increase security.

How to Get Started

This project is a starting point for Firebase application development and below are a few resources to get you prepared before starting this project:

Online documentation is essential and it offers tutorials, samples, guidance on mobile development, and a full API reference. However, You can check on the Firebase documentation.

Photo Preview

Glossary

  • Firebase – is a Backend-as-a-Service (Baas) because It provides developers with a variety of tools. Also, services to help them develop quality apps, grow their user base, and earn a profit.
  • Authentication – Authentication is the process of determining whether someone or something is, in fact, who or what it declares itself to be. For instance, Authentication technology provides access control for systems. Checking to see if a user’s credentials match the credentials in a database of authorized users or in a data authentication server
  • Verification – is the process of checking user details are correct. For instance, the password field and confirming the password is correct.
  • A Reference – represents a specific location in your Database. It can be used for reading or writing data to that Database location.
  • Intent – In android, an intent is a software mechanism that allows users to coordinate the functions of different activities to achieve a task. As a result, It allows one to navigate within activities easily.

Steps:

Step 1: Connecting android studio project to Firebase

Firstly, let’s connect the android studio to Firebase and we will be using user email. We will then connect our project to the Firebase. Since we will be using Firebase services such as Firebase Authentication, Firebase real-time database, and Firebase storage.

To connect with your email.

  1. On the top left of the menu, toolbar click on it. Click “add account”.
  2. You will be directed to log in to your email.
  3. Enter the email and password.
  4. Click on Firebase console.


Once connected your project should have your email as shown below in the image.

How to create an android two step authentication signup system using Firebase

To connect to Firebase services.

  1. On the android studio, click on the Tools menu.
  2. Then click on Firebase.
  3. A menu containing Firebase services will appear on your right.
  4. Click on Firebase Authentication. Connect to Firebase.
  5. Enter the name of your project and click on email and password to add Firebase authentication dependencies.
  6. Click on the real-time database, then on save and retrieve data.
  7. Lastly, click on storage “upload and download a file with cloud storage”

As a result, all Firebase dependencies are added to your project.

How to create an android two step authentication signup system using Firebase
//firebase dependencies
implementation 'com.google.firebase:firebase-auth:16.0.5'
implementation 'com.google.firebase:firebase-storage:16.0.4'
implementation 'com.google.firebase:firebase-database:16.0.4'
//firebase dependencies

The first is used for Firebase authentication and more so the version will depend on the version android studio you are using. Moreover, you can use a higher version or stick to this.

To allow a user to sign in with email and password.

  1. Go to Firebase console.
  2. Choose your application
  3. Click on authentication on the left side menu.
  4. Sign-in method.
  5. Enable email/password.
How to create an android two step authentication signup system using Firebase

By default, your database rules require Firebase Authentication while Grant full read and write permissions only to authenticated users. The default rules ensure your database isn’t accessible by just anyone. Once you’re set-up, you can customize your rules to your needs. In this case, in order to write and read from Firebase. We will allow full user permission.

  • On the Firebase console right menu.
  • Click on the database.
  • Then User and permissions.
  • Write this code shown below to allow permissions.
// These rules  allow anyone read or write access to your database
{
  "rules": {
    ".read": true,
    ".write": true
  }
}

build.gradle(Module: app) project dependencies.

We are going to add some dependencies purposely for designing a good user interface.

implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'de.hdodenhof:circleimageview:3.0.2'

Step 2: Designing the home Activity

This will be the final page. “Home”. Because we will land here after the two-step authentication. In order to complete our stages, we will first design this page so that after completing the second step of authentication we will land here.

Step 3: Designing First step Authentication

It will involve registering user information via email and password. Create a step_one_authentication activity to hold the user registration information.

It contains three edit texts, three text views, and one button, and most importantly these fields, “email, password and confirm password”.

On the stepOneAuthentication let’s allow the user to register via email and password. We will also make sure that the user does not leave any of the fields blank and also confirm that the password and password confirm matches.

if (TextUtils.isEmpty(Email)){
                Toast.makeText(Register.this, "Please enter your email...", Toast.LENGTH_SHORT).show();
            }
else if(TextUtils.isEmpty(Password)){
                Toast.makeText(Register.this, "Please enter your password...", Toast.LENGTH_SHORT).show();
            }
else if (TextUtils.isEmpty(PasswordConfirm)){
                Toast.makeText(Register.this, "PLease confirm your password...", Toast.LENGTH_SHORT).show();
            }
else if(!Password.equals(PasswordConfirm)){
                Toast.makeText(Register.this, "Password do no match...", Toast.LENGTH_SHORT).show();

            }

We will use a Firebase method as shown below to allow registering through email and password and if the task is successful, the user is directed to second step authentication. If not an error message pops up.

 mAuth.createUserWithEmailAndPassword(Email,Password)
  .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
 @Override
 public void onComplete(@NonNull Task<AuthResult> task) {
 //checking if the task is sucessful
if(task.isSuccessful()){                                       SenduserToSTepTwoAuthentication();                                     Toast.makeText(Register.this, "You have passed the first  step authentication...", Toast.LENGTH_SHORT).show();
 loadingBar.dismiss();
  }
else{
  String message = task.getException().getMessage();                                   Toast.makeText(Register.this, "error occured" + message, Toast.LENGTH_SHORT).show();                                   }
loadingBar.dismiss();
 }
 });


Step 4: Designing Login Activity

Only users who have passed the first step authentication can log in to the system. For instance, if you enter your email and password, these fields are authenticated. If they exist in the Firebase authentication real-time database, the user is directed to the second step authentication.

How to create an android two step authentication signup system using Firebase

Login user interface code looks like:

FirebaseUser currentUser = mAuth.getCurrentUser();

Gets the current User. For instance, the user who has just has registered

currentUser !=null

Ensures that the user is not equal to null. If a user is null. He is prompted to register.

Step 5: Step-two Authentication

After successful verification of email and password, a user is directed to step-two authentication. This step will involve providing more information about the user before heading to the home activity of the system. For instance, in our case will do this by allowing the user to provide his/her first name, other names, and his/her phone number.

We will use the shown below method to store data in the Firebase database. It holds two variables. The first one is the name of the field such as the “the heading”. Second is the value stored.

HashMap userMap = new HashMap();
userMap.put("FirstName",firstname);
userMap.put("OtherName",othernames);
userMap.put("Phone",phonenumber);



Step 6: Home Activity Authentication

Here we have to check the User Existence in the Firebase database. For instance, if the user provides both email and password in the first step authentication. Additional information in the second step authentication, he accesses the home activity. Otherwise, access is denied.

To check user existence in the Firebase database. We are going to use “DataSnapshot”. DataSnapshot is used to fetch data from the node whenever a listener event is triggered by the database. In this case, we will use it to check if the user exists in the database.

Since the first method of authentication, email, and password are not stored in the Firebase database. Therefore, we get the current user Id and use DataSnapshot to check if he has registered.

If a user exists in the Firebase database, that is he has already registered via email and password and has provided step two authentication information. He is directed to the home page else he is directed to step two authentication.

private void CheckUserExistence()
{
//get the user id
final String currentUserId =mAuth.getCurrentUser().getUid();
 userRef.addValueEventListener(new ValueEventListener() {
  @Override
 public void onDataChange(@NonNull DataSnapshot dataSnapshot)
 {
  if (!dataSnapshot.hasChild(currentUserId)){
  //user is authenticated but but his record is not present in real time firebase database
   SendUserToStepTwoAuthentication();
   }
  }
 @Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
 });


Explanation of methods.

mAuth = FirebaseAuth.getInstance();
mAuth = FirebaseAuth.getInstance();
userRef =FirebaseDatabase.getInstance().getReference().child("Users");

Gets the default Firebase Database instance. In this case it creates an instance once a user registers.

//get reference
//import statement
import com.google.firebase.database.DatabaseReference;
//crating an object of the method
userRef = FirebaseDatabase.getInstance().getReference()

Database Reference for the database root node.

//get current user
FirebaseUser currentUser = mAuth.getCurrentUser();

This method gets the user who have just logged in.

//createUserWithEmailAndPassword
mAuth.createUserWithEmailAndPassword(Email,Password)
  .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
  @Override
public void onComplete(@NonNull Task<AuthResult> task) {
   //checking if the task is sucessful
   if (task.isSuccessful()){
   SenduserToSTepTwoAuthentication();
   Toast.makeText(Register.this, "You have passed the first step authentication...", Toast.LENGTH_SHORT).show();
   loadingBar.dismiss();
  }
  else{
  String message = task.getException().getMessage();
   Toast.makeText(Register.this, "error occured" + message, Toast.LENGTH_SHORT).show();                                   }
  loadingBar.dismiss();
}
});

Creates a new user. Uses email and password.

//sign in with email and password
mAuth.signInWithEmailAndPassword(email,password)
           .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
               @Override
               public void onComplete(@NonNull Task<AuthResult> task) {

                   if (task.isSuccessful()){
                       SendUserToMainActivity();
                       Toast.makeText(Login.this, "You are logged in successful", Toast.LENGTH_SHORT).show();
                       loadingBar.dismiss();
                   }
                   else
                   {
                       String message = task.getException().getMessage();
                       Toast.makeText(Login.this, "error occurred" +message, Toast.LENGTH_SHORT).show();
                       loadingBar.dismiss();
                   }

               }
           });

Allow user to login. Uses email and password.

Intents

We are going to use intents to navigate through project activities. Check more about Implicit Intent and Explicit Intents.
Import statement for intent is as shown below.

import android.content.Intent;

Creating the intent.

Intent mainIntent = new Intent(Register.this,MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);

Adding a Progress bar

Let’s add a progress bar. This is to allow a user to know what’s happening as he waits to login.
Import statement.

import android.app.ProgressDialog;

Initializing and creating an instance

 loadingBar =new ProgressDialog(this);

setting the loading bar details and dismissing it.

 //progress bar
            loadingBar.setTitle("Log In");
            loadingBar.setMessage("please wait...");
            loadingBar.show();
            loadingBar.setCanceledOnTouchOutside(true);
//dismissing progress bar
 loadingBar.dismiss();

By this we have completed our two-step authentication signup system with Firebase. Click on the Run button and Run the application on your android phone but you can also install an android emulator on the android studio.

Reflective Analysis

After doing this project, I learned more about how Firebase services. It has very strong services. It can help you create real-time quality apps. It’s very easy to store user sessions.

Future Directions

  1. Add Phone Number Authentication allowing you to receive a text message to verify your phone number.
  2. Add email link authentication. To enable the validity of user emails we can allow Firebase to send an email verification link.

Learning Strategies and Tools

There are a lot of learning tools online, I would recommend the following:

I used the learning tools above. I also used PDF documentations to achieve this. Anytime I faced some bugs, I would use stack overflow to check for solutions. I was able to work with Intents.
Make sure you have an active internet connection since Firebase is an online database.
It took me a total of 12 hours to finish the project and the blog.

Get the complete project from GitHub
Happy Coding!!