Firebase

Firebase – Basic Authentication

Hello droiders, welcome to the fourth part of this tutorial series on Firebase. A quick glimpse of previous parts:

  • Part 1, Firebase – Cloud Messaging, formerly known as Google Cloud Messaging, is a new and improved way of delivering Push Notifications to major platforms that includes Android, iOS and web.
  • Part 2, Firebase – Crash Reporting, a comprehensive tool to receive detailed information about the Crash.
  • Part 3, Firebase – Storage, a storage for app developers like us, comes with storage backed with Google Cloud Storage

Authentication is one of the most essential features in any area, be it an application or a website. So, first let us understand what is meant by authentication.

Authentication is the process of proving a user’s identity. Authentication is required in every application in order to keep one’s private data secure.

Introduction

Firebase Authentication makes developers life easy by providing Simpler and Faster way of authentication using Firebase SDKs. Also, its a child play to use them. If its not, we will make it for you 🙂

Firebase provides following types of authentication:

  • Email and password based authentication – Basic Authentication
  • Federated identity provider integration – Social Login based Authentication
  • Anonymous authentication
  • Custom auth system integration
  • Firebase UI

In This Post

Today, we are going to talk about how to work with basic authentication. In basic Authentication, we authenticate users with their Emails and Passwords.

In this demo, we are going to achieve following tasks:

  • Login a User
  • Sign Up a user
  • Forgot Password
  • Update Profile
  • Change Email
  • Change Password
  • Re-Authenticate user
  • Logout a user

Getting Started

Pre-requisites

  • Android Studio 1.5 or above
  • Google Play Services 9.0.2 or above.

Add Firebase to your app

    1. Go to Firebase console and click on “CREATE NEW PROJECT”. Fill the “Project Name” and Select Country, then click on “CREATE PROJECT”cropped1

 

    1. Click on “Add Firebase to your Android app”cropped2

 

    1. Enter Package name and Debug signing certificate SHA-1(Optional) and click on “Add app” buttoncropped3
    2. Google-services.json file will be downloaded. Go to Android Studio and Switch to the Project view in Android Studio to see your project root directory. Move the google-services.json file you just downloaded into your Android app module root directory.cropped4
    3. The Google services plugin for Gradle loads the google-services.json file you just downloaded. Modify your build.gradle files to use the plugin.

 

  1. Add the following lines, to your Project-level build.gradle (/build.gradle):
    buildscript {
        dependencies {
            // Add this line
            classpath 'com.google.gms:google-services:3.0.0'
        }
    }
    
  2. Add the following lines to the bottom of your App-level build.gradle:
    apply plugin: 'com.google.gms.google-services'
    
  3. Add the following dependencies, to your App-level build.gradle
    compile 'com.google.firebase:firebase-auth:9.2.0'
    
  4. Finally, press “Sync now”.

Code

In your activity, initialize FirebaseAuth by getting instance as below:

private FirebaseAuth mFirebaseAuth;
...
mFirebaseAuth = FirebaseAuth.getInstance();

Optionally, you can register a listener for change in state of Auth. For that, initialize AuthStateListener as below:

private FirebaseAuth.AuthStateListener mAuthStateListener;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
    // ...
    mAuthStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User signed in. Now, You can get UserId by calling firebaseUser.getUid() and save it in preference
            } else {
                // User signed out. Now, You can clear the preference.
            }
            // ...
        }
    };
    // ...
}

Sign up a User:

        mFirebaseAuth
                .createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            Toast.makeText(SignUpActivity.this, "Registration Successful", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(SignUpActivity.this, HomeActivity.class));
                        } else {
                            Toast.makeText(SignUpActivity.this, task.getException().getMessage(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });

Login a User:

        mFirebaseAuth
                .signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {

                        DialogUtils.dismissProgressDialog();

                        if (task.isSuccessful()) {
                            Toast.makeText(LoginActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                            finish();
                        } else {
                            Toast.makeText(LoginActivity.this, task.getException().getMessage(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });

Send Password Reset Link:
FirebaseAuth provides password reset feature. It can be implemented as below:

        mFirebaseAuth.sendPasswordResetEmail(mEditEmail.getText().toString())
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        DialogUtils.dismissProgressDialog();
                        if (task.isSuccessful()) {
                            Toast.makeText(ForgotPasswordActivity.this, "An email has been sent to you.", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(ForgotPasswordActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });

Update a User Profile:

        UserProfileChangeRequest.Builder builder = new UserProfileChangeRequest.Builder();
        builder.setDisplayName(mEditText.getText().toString());
        if (mUri != null) {
            builder.setPhotoUri(mUri);
        }
        UserProfileChangeRequest profileUpdates = builder.build();

        mFirebaseUser.updateProfile(profileUpdates)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isSuccessful()) {
                            showToast("Profile Updated Successfully.");
                        }
                    }
                });

Change Email:
You can change email by following as below, but there is a case. If you want to perform some security concerned actions such as Changing email address, changing password or deleting account, those actions require that User should be recently signed in. If user has not re-logged in for long time, then, we need to re-authenticate the user. After, successful authentication, you will be able to change email.

         mFirebaseUser.updateEmail(email)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isSuccessful()) {
                            showToast("Email updated successfully.");
                            return;
                        }

                        if (task.getException() instanceof FirebaseAuthRecentLoginRequiredException) {
                            FragmentManager fm = getSupportFragmentManager();
                            ReAuthenticateDialogFragment reAuthenticateDialogFragment = new ReAuthenticateDialogFragment();
                            reAuthenticateDialogFragment.show(fm, reAuthenticateDialogFragment.getClass().getSimpleName());
                        }
                    }
                });

Change Password:
You can change password by following as below, but there is a case. If you want to perform some security concerned actions such as Changing email address, changing password or deleting account, those actions require that User should be recently signed in. If user has not re-logged in for long time, then, we need to re-authenticate the user. After, successful authentication, you will be able to change password.

        mFirebaseUser.updatePassword(password)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isSuccessful()) {
                            showToast("Password updated successfully.");
                            return;
                        }

                        if (task.getException() instanceof FirebaseAuthRecentLoginRequiredException) {
                            FragmentManager fm = getSupportFragmentManager();
                            ReAuthenticateDialogFragment reAuthenticateDialogFragment = new ReAuthenticateDialogFragment();
                            reAuthenticateDialogFragment.show(fm, reAuthenticateDialogFragment.getClass().getSimpleName());
                        }
                    }
                });

Re-Authenticate a user:
To re-authenticate user code as below:

       FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        AuthCredential authCredential = EmailAuthProvider.getCredential(email, password);
        firebaseUser.reauthenticate(authCredential)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isSuccessful()) {
                            dismiss();
                        } else {
                            ((BaseAppCompatActivity) getActivity()).showToast(task.getException().getMessage());
                        }
                    }
                });

Finally, Logout a user:

        mFirebaseAuth.signOut();

Conclusion

Authentication has never been so easy to implement. I must say, Firebase Authentication is worth to go for it. Until we meet again in next part, Happy Firebasing 🙂

Demo

Firebase Authentication Basic

Want to work with us? We're hiring!
  • Nice Chintan appreciated !! Keep it up with same outstanding Posts.

    • Chintan Soni

      Thanks for appreciation.. 🙂