Firebase User Authentication in Android

Firebase User authentication
Firebase provides more features as described in previous post. One of the very useful feature is User Authentication. Different types of User Authentication are,
  1. Email and Password Authentication
  2. Google Plus Authentication
  3. Facebook Authentication
  4. Github Authentication
In this post, I will explain the way to implement Firebase Email & Password authentication. To demonstrate how simplified and easy to use Firebase is, we will build a simple login / register (Firebase Authentication) demo. This separates sensitive user credentials from your application data, and lets you focus on the user interface and experience for your Application. It is suitable for Simple, Easy and Perfect way of handling Login, Registration, Forget Password and so on.

The Feature and Settings up of Application in Application is Explained in Previous post. After creating the project, Enable Firebase Email & Password authentication by selecting Authentication in Left Pane in Firebase Console and Go to Sign-in-Method as in the following Image.

Enable Authentication

I. Creating and Setting up Android Project

1. Create a new project in Android Studio from File ⇒ New Project. When it prompts you to select the default activity, select Blank Activity and proceed. While filling the project details, use the same package name which you gave in Firebase console.

2. Open AndroidManifest.xml and add the INTERNET permission as we need to make network calls.
<uses-permission android:name="android.permission.INTERNET" />

3. Paste the google-services.json file to your project’s app folder. This step is very important as your project won’t build without this file.

4. Now open the build.gradle located in project’s home directory and add firebase dependency.
build.gradle
dependencies {
 classpath 'com.android.tools.build:gradle:2.1.2'
 classpath 'com.google.gms:google-services:3.0.0'
}
5. Open app/build.gradle and add firebase auth dependency. At the very bottom of the file, add apply plugin: ‘com.google.gms.google-services’
app/build.gradle
dependencies {
    compile "com.google.firebase:firebase-auth:9.0.2"
}
apply plugin: 'com.google.gms.google-services'

II. Coding Part

1. Sign Up Method:

In Firebase Authentication, the credits entered by user might have some validation. For Example, Email ID might be in Proper email format and Password must have at-least 6 character. Firebase Provides createUserWithEmailAndPassword() to create New User in Firebase.
// Validating Credits entered by User with Firebase
btnSignUp.setOnClickListener(new View.OnClickListener() {
 @Override
    public void onClick(View view) {
  final String email = inputEmail.getText().toString();
  final String password = inputPassword.getText().toString();
  try {
   // Email ID must be valid
   // Password strength is minimum 6 characters by default in firebase registration
   // Minimum Password length throws Error as 'WEAK PASSWORD'
   if (password.length() > 0 && email.length() > 0) {
    PD.show();
    //authenticate user
    auth.createUserWithEmailAndPassword(email, password)
     .addOnCompleteListener(RegisterActivity.this, new OnCompleteListener() {
      @Override
      public void onComplete(@NonNull Task task) {
      if (!task.isSuccessful()) {
       Toast.makeText(
       RegisterActivity.this,
       "Authentication Failed",
       Toast.LENGTH_LONG).show();
      } else {
       Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
       startActivity(intent);
       finish();
      }
      PD.dismiss();
     }
    });
   } else {
     Toast.makeText(
      RegisterActivity.this,
      "Fill All Fields",
      Toast.LENGTH_LONG).show();
   }

  } catch (Exception e) {
   e.printStackTrace();
  }
 }
});

2. Sign In Method:

Firebase provides signInWithEmailAndPassword() method to sign in the user.
// Validating Login Credits with Firebase
btnLogin.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View view) {
  final String email = inputEmail.getText().toString();
  final String password = inputPassword.getText().toString();
  try {
   if (password.length() > 0 && email.length() > 0) {
    PD.show();
    // Authenticate user
    auth.signInWithEmailAndPassword(email, password)
      .addOnCompleteListener(LoginActivity.this, new OnCompleteListener() {
       @Override
       public void onComplete(@NonNull Task task) {
        if (!task.isSuccessful()) {
         Toast.makeText(
           LoginActivity.this,
           "Authentication Failed",
           Toast.LENGTH_LONG).show();
         Log.v("error", task.getResult().toString());
        } else {
         Intent intent = new Intent(LoginActivity.this, MainActivity.class);
         startActivity(intent);
         finish();
        }
        PD.dismiss();
       }
      });
   } else {
    Toast.makeText(
      LoginActivity.this,
      "Fill All Fields",
      Toast.LENGTH_LONG).show();
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
});

3. Forget Password:

Firebase provides sendPasswordResetEmail() method to reset password. Automatically, Reset Password email send to your entered email. To reset password, Click the link in your email. We can customize the Email Template.
// Method to Reset Password or Forget Password Option
auth.sendPasswordResetEmail(modeStr).addOnCompleteListener(new OnCompleteListener() {
 @Override
 public void onComplete(@NonNull Task task) {
  if (task.isSuccessful()) {
   Toast.makeText(ForgetAndChangePasswordActivity.this, "We have sent you instructions to reset your password!", Toast.LENGTH_SHORT).show();
  } else {
   Toast.makeText(ForgetAndChangePasswordActivity.this, "Failed to send reset email!", Toast.LENGTH_SHORT).show();
  }
  PD.dismiss();
 }
});

4. Change Username or Password:

Firebase provides updatePassword() to change password and updateEmail() to change Email ID.
// Method to change Password Option
user.updatePassword(modeStr)
 .addOnCompleteListener(new OnCompleteListener() {
  @Override
  public void onComplete(@NonNull Task task) {
   if (task.isSuccessful()) {
    Toast.makeText(ForgetAndChangePasswordActivity.this, "Password is updated!", Toast.LENGTH_SHORT).show();
   } else {
    Toast.makeText(ForgetAndChangePasswordActivity.this, "Failed to update password!", Toast.LENGTH_SHORT).show();
   }
   PD.dismiss();
  }
 });
 
// Method to Change Email or Username Option
user.updateEmail(modeStr)
 .addOnCompleteListener(new OnCompleteListener() {
  @Override
  public void onComplete(@NonNull Task task) {
   if (task.isSuccessful()) {
    Toast.makeText(ForgetAndChangePasswordActivity.this, "Email address is updated.", Toast.LENGTH_LONG).show();
   } else {
    Toast.makeText(ForgetAndChangePasswordActivity.this, "Failed to update email!", Toast.LENGTH_LONG).show();
   }
   PD.dismiss();
  }
 });
 

5. Delete User or Account:

Firebase Provides delete() method to delete account.
// Method to Remove Account Option
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
 user.delete()
  .addOnCompleteListener(new OnCompleteListener() {
   @Override
   public void onComplete(@NonNull Task task) {
    if (task.isSuccessful()) {
     Toast.makeText(ForgetAndChangePasswordActivity.this, "Your profile is deleted:", Toast.LENGTH_SHORT).show();
    } else {
     Toast.makeText(ForgetAndChangePasswordActivity.this, "Failed to delete your account!", Toast.LENGTH_SHORT).show();
    }
    PD.dismiss();
   }
  });
}

6. Sign out Session:

Firebase provides signOut() method to Sign out from Firebase session.
// Sign-Out option
btnSignOut.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View view) {
  auth.signOut();
  // this listener will be called when there is change in firebase user session
  FirebaseAuth.AuthStateListener authListener = new FirebaseAuth.AuthStateListener() {
   @Override
   public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
    FirebaseUser user = firebaseAuth.getCurrentUser();
    if (user == null) {
     startActivity(new Intent(MainActivity.this, LoginActivity.class));
     finish();
    }
   }
  };
 }
});

7. Checking User Session:

The following method is used to check User is Signed In or Not.
//Checking user is present or not
FirebaseAuth auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
 Log.v("Session", "Signed In");
}

Download Source Code

In this, I explained each method to handle firebase Email/Password method and am not explaining the layout of each screen in this Project. For more, Details Please download whole project source from Github.

Download From Github

If you find this post is useful, Please provide star in Github and Having any trouble or doubt while using this project leave your comment.

Share this

Related Posts

Previous
Next Post »

2 comments

comments
14 April 2019 at 19:43 delete

How we can do this in xamarin.forms or in shared PCL proect

Reply
avatar

Please Comment about the Posts and Blog