Shares

Firebase Authentication by Example with Android

Shares
Firebase Authentication with Android

This post is a step by step tutorial on how to implement Firebase Authentication in Android. According to official documentation Firebase authentication provides simple free, multi-platform sign-in. It provides an end-to-end identity solution, supporting Email/password accounts, phone auth, Google, Twitter, Facebook, GitHub login and more. The usefulness of Firebase Authentication goes beyond sign-in, it provides user management features such as password reset, sign-out, new account creation, account recovery, and merging. And, it does all these using industry best practices.

There are two components to Firebase Authentication: the client SDK that you add to your client app and there are versions for Android, IOS, and Web. Then there is the backend service which provides the authentication services and communicates back to the client. The way Firebase Authentication work is that it creates a unique user object for each authenticated user called Firebase User regardless of the login method that the user logged in from. Once this user object is created, Firebase Authentication manages the user login session for you and the user can log into your app from any other device, and Firebase Authentication will associate the user with the same user object as long as the user logged in with the same login method.

Steps to Implement Firebase Authentication to Android Project

The steps to implement Firebase will vary slightly depending on the client platform (Android, IOS or The Web) and whether you are using FirebaseUI or you are doing a manual implementation. We will discuss FirebaseUI later but first here are the general steps that are required to implement Firebase Authentication.

  1. Create a Firebase account if one does not exist.
  2. Create a Firebase project if one does not exist.
  3. Create an Android project if one does not exist.
  4. Connect your Android Studio project to the Firebase project.
  5. Add Firebase Authentication client SDK to Android Studio project.
  6. Enable the authentication method or methods that you want to use, eg Email, Facebook, Twitter, Google, etc.
  7. If using Email login method, obtain authentication credentials from the user such as email or password and use the client SDK to pass it to Firebase Authentication backend service.
  8. If using a federated provider such as Google or Facebook, then obtain an OAuth token from them and use the client SDK to pass it to Firebase Authentication backend service.
  9. The Firebase Authentication service will verify the provided information and return a success or failure response to the client SDK.
  10. If the response is successful, then you will have a valid Firebase User object that you will work with on the client or pass to your backend server to satisfy further business rules or logic.

Create Firebase Account and Project

Creating a Firebase account is a simple process. Just go to https://firebase.google.com and click on the Sign In button on the top left-hand side.

You will see the familiar Google account authentication workflow from where you can login with your existing Google account or create a new one if none exists. Once you sign in, you will be brought back to the same page where you started. From here you can now click on Go To Console button on the top left-hand side of the page, and it is in the console that all the action happens.

In the Firebase console, you will see a list of the projects that you have already created if one exists and also a button with the label Add new project. When you click on the Add Project button, you will be presented with this dialog below where you can enter your project name and select your country/region.

For our demo app, I will go ahead and enter Pronto Notepad as the project name and choose the default country USA as my region. Click Enter after you enter the project name you will be brought to the Firebase Console. Take a few moments to familiarize yourself with the console if this is your first time of accessing it because you will be coming back very often to it as we go through this post and as you continue to work with Firebase.

Create New Android Studio Project

To continue learning about Firebase Authentication in this blog post, we will create a demo Android Notepad app.  This demo app will  display sample notes like this:

Android Notepad App

Android Notepad App with Firebase

This demo app has a simple workflow, when the app launches if the user is logged in, we show a list of Notes but if the user is not logged in, we show a login screen. This demo app will consist of three Activities which are the NoteListActivity to display a list of Notes, AuthUIActivity to implement Authentication using FirebaseUI library and EmailPasswordLoginActivity to implement email and password login manually. But first, we have to create an Android Studio project. Go ahead and create a brand new Android Studio project and name it Pronto Notepad if you want to follow along with the sample codes in this book you should change the name of your MainActivity to NoteListActivity. Run your blank project in an emulator or device to ensure that it builds before you proceed.

To better demonstrate the features of Firebase Authentication, we will add a Navigation Drawer using Mike Penz’s Material Drawer with the following buttons:

  1. Notes
  2. Sign In
  3. Sign Out
  4. Delete Account

We will also remove the settings icon, the Floating Action Button and update the theme color. Here is a before and after screenshot of the app at this point.

The code for that screenshot is included in the source code found at the end of this post. A complete Notepad app source code is included with my book Pronto Firebase. The code below shows what the NoteListActivity should be looking like now.

 

Earlier, I stated that there are two components to Firebase Authentication: the client SDK and the backend service. We hook into the backend service via the project that we created on Firebase Console, and we use the client SDK by adding it to the client project. In Android, libraries are usually added through Gradle dependencies. Therefore, to add Firebase Authentication to our Android project we need to add the corresponding Gradle dependencies. By the time of this writing, the Firebase client SDK is at version 11.2.0 so the Firebase Authentication Gradle dependency is compile 'com.google.firebase:firebase-auth:11.2.0'.  However, before we add this to our project, we need to discuss the library that we will use to work with Firebase Authentication which is called FirebaseUI.

Introduction to FirebaseUI

While it is true that Firebase Authentication provides the SDK and API for us to implement authentication and user management in our app, we still have to write the code for the implementation. FirebaseUI is a done for you open source library that makes it very easy to use Firebase. Using FirebaseUI significantly reduces the amount of code you will write to implement authentication, and most importantly, FirebaseUI follows recommended best practices that would have been a challenge for you to implement on your own.

The usefulness of FirebaseUI goes beyond authentication; it also works with Firebase Database and Storage. Also, there are FirebaseUI libraries for IOS and The Web, however, we will be using FirebaseUI library for Android in this post. To better understand the productivity gain that FirebaseUI provides, take a look at the Android Authentication flow chart below that represents possible login workflow.

Now imagine the amount of code you will write to implement that workflow, that is part of what you get when you use FirebaseUI. The Firebase documentation recommends that you use FirebaseUI instead of using Firebase Authentication directly and so do I. However, in another section for the sake of completion, I will also show you how you can implement Email Authentication manually should you have a need to do so. To learn more about FirebaseUI Authentication click here. At this point, you may be wondering what library we should add? The answer is one because FirebaseUI library has a transient dependency on the Firebase library it is working with, therefore by adding FirebaseUI Auth library you are also pulling in the corresponding version of Firebase Auth library. Add the line of code below to your app module gradle file.

Connect Android Studio to Firebase Project

There are two ways to connect Android Studio project to Firebase Console project, you can initiate the connection from the Firebase side, or you can launch the connection from the Android side, Either way, the important thing is that a file named google-services.json need to be generated, and this file needs to be added to Android Studio. To initiate the connection from Firebase Console, you need to click on one of the three buttons in the screenshot below. For us, that would be the second button for Android.

Once you click on the button, you will be presented with a dialog window to enter some information about your project from which the Firebase tooling will generate the JSON file for you. You will then need to download the JSON file and place it in your Android project. While this process is simple, I prefer the second approach which is simpler. To initiate the connection from Android Studio, first, you need to ensure that you are signed into Android Studio. To check if you are signed in, look at the top right-hand corner of Android Studio, you should see your Google account profile picture if you are signed in, if not then click on the login (see screenshot below) and then sign into your Google account and close the login screen.

 

 

Once you are signed into Android Studio, then you can use Android Firebase Assistant to add your Android Studio project to Firebase Console project. In the video below I show you how you can initiate the connection from Android Studio.

Enable Firebase Authentication

Now that our Android Studio project is connected to our Firebase Console project, the next step is to tell Firebase which Authentication methods we intend to use. To do this, simply go the Firebase Console and click on the Authentication tab on the left and then click on Sign Methods in the middle and you will see the various Authentication options that Firebase provides as shown in the screenshot below.

 

 

In this post, we will implement Email, Google, Facebook and Anonymous logins so go ahead and enable only the Email and Google logins for now. Email login works by default out of the box; Google account is a first class citizen in the Android world so it requires very minimal configuration to work. Facebook, however, require additional steps and we will cover that in another section. We will also discuss Anonymous Authentication later before we enable it.

Requiring Users to Login to Your App

When we implement authentication to our app, what we are in effected doing is putting our app behind a login wall such that anyone requiring access to the app or content will have to go through a login process. Mobile app users, however, do not like to be asked to log in so the question then is at what point in your app should you require users to login. That is a decision you have to make based on the business needs of your app,  some popular apps like Facebook require users are to login to use the app while apps like Youtube allows users to use the core features of the app like watching videos while certain actions like uploading a video require sign-in.

For this Firebase Authentication tutorial, we will require users that users login to use the app. There are two components of Firebase that allows us to implement login required feature and they are they are FirebaseAuth object and FirebaseUser object. Regardless of which Authentication method you use, a FirebaseUser object will always be created if the login was successful. Therefore, at any time if this FirebaseUser object is null that means that the user is not logged in and if it is valid, that means that the user is logged in.

To require users to log in, therefore, we need to go to the entry point to our app which in our case is the onCreate() method of the NoteListActivity and perform a check as shown in the code sample below.

In the above code example, we got an instance of the FirebaseAuth object, and then from it, we retrieved the FirebaseUser object. If the user is currently logged in, that user object should be valid if not it should be null. If the user is logged in, we allow them to proceed with the rest of the app, however, if the user object is null, we then send the user to another screen for them to log in, we will create that login screen next.

Implement Email and Google Login

The login screen for this demo app will be called AuthUIActivity.java; when users who are not logged in arrive at the app they will be sent to this screen to log in. This screen is implemented using FirebaseUI.  The goal of this Activity will be to help new users of our app to create an account and to help existing users to log in. If you are following along with this tutorial then add an empty Activity to your app with blank content as shown below.

The workflow for the AuthUIActivity can be summarized with the following three steps:

  1. Step 1 – When a user arrives at this Activity, we once again check the login status of the user. If the user is already logged in, then there is no need to proceed with the Activity. However, if the user is not logged in, then we can proceed.
  2. Step 2 – Collect the user’s credentials, it could be their email and password or their Federated user account which could be Google or Facebook and send to Firebase Authentication backend service for authentication.
  3. Step 3 – Listen for a response from Firebase Authentication backend service and handle the response.

Here is how we implement Step 1 above, same thing we did on NoteListActivity.

To implement Step 2 above is where FirebaseUI truly shines. It has an AuthUI object that does the bulk of the work for us. Essentially all we do is tell this AuthUI object what Authentication method we want to use like Email, Facebook, Google, Twitter, Github, etc. Once we do that, it creates the user interface and handles all the authentication workflow for us. Here is an abbreviated sample code of how we use FirebaseUI to implement Step 2.

The main thing happening in this code is that we passed a list of the login methods we want to support to the AuthUi builder. For this demo, we are implementing Email, Google, and Facebook logins. I have added a generic logo just to make good use of the white space above the login methods. The FirebaseUI Github project has documentation and code sample of other parameters to the AuthUI builder. Please note that if you run the app at this point it will not build because you have not added the Facebook SDK and we will do that soon. However, after adding the Facebook SDK and running the app, here is what the screen for the AuthUIActivity will look like.Firebase Authentication ScreenFrom here on, the FirebaseUI takes care of responding to any button that the user clicks including collecting the user email and password, determining if this is a returning user or a new user and all the other tasks associated with login including sending the credentials to Firebase Authentication backend service. FirebaseUI also provides a helper class called IdpResponse that encapsulates the result of authentication. What you do with the result of the Authentication is up to you. The AuthUIActivity gets the response of the authentication in the onActivityResult callback method and here is how you can handle it.

And believe it or not, that is all we need to do to implement authentication to our app using FirebaseUI. In the code block above, all we do is that if the authentication succeeded we go back to the NoteListActivity knowing that we now have a valid FirebaseUser object. If the authentication failed, we surface the appropriate error message to the user via Snackbar. I have added the error message to the String resource file. And by the way, I copied those directly from the sample app that comes with FirebaseUI.

Implement Facebook Authentication

In general, people do not like to create new accounts for each site or app they use; most people prefer to use their social media accounts such as Facebook to login. Therefore, it is a no-brainer to add Facebook login as an option to our app. Here are additional steps that we need to take to implement Facebook login to our Android app.

  1. Add Facebook SDK
  2. Create Facebook App
  3. Update Firebase Console
  4. Add Facebook ID to String resource
  5. Add Facebook Login option to our Login screen

To add Facebook SDK, we need to add the following line to the dependencies section of our app Gradle file compile('com.facebook.android:facebook-android-sdk:4.25.0')  Rebuild the app and ensure that it can build before proceeding. To create a Facebook App you need to login to Facebook developer dashboard or register for an account if you do not have one. Facebook has a getting started guide on how to create a Facebook app for Android however here are few points to note as you create Facebook App.

  1. You may want to give your Facebook app the same name as your Android app for consistency
  2. You should add Android as a Platform to your app
  3. You should generate a Hash key on your development machine and copy and paste that into the Hash Key field under the Android platform entry. Here is a StackOverflow question on how to generate a Hash key for your operating system.
  4. You need to add a Facebook Login product to your Facebook app that you just created.
  5. Then, you will copy the OAuth redirect link that you will get from Firebase console for your app and paste into the redirect box in the Facebook Login product you added.
  6. You will need to copy both the app Id and app secret for the App you just created from Facebook to Firebase console.
  7. You need to copy the Facebook app Id to your Android project.

You enable Facebook Authentication method the same way you enabled Email and Google in Firebase Console. Toggle the Enable button to enable and then as outlined above, you then need to copy the OAuth link from here and paste into Facebook. You also need to copy the app Id and secret from Facebook and paste into the boxes as shown in the screenshot below. Click the Save button to save when you are done.

The next step is to copy the App ID from Facebook and paste into the String resource file, exactly like below. Please note that if you for some reason you have copied from FirebaseUI demo app it may not work, this format is the one that works.

<string name=”facebook_application_id” translatable=”false”>09876543211234</string>
<string name=”facebook_login_protocol_scheme” translatable=”false”>fb09876543211234</string>

Once you do, rebuild your project and run it. Go ahead and test it and ensure that you can login with Facebook, Email, and Google.

Summary

This tutorial has been an excerpt from my book Pronto Firebase – Practical Guide on Firebase Mobile Platform with Androidoid. In the book I covered Anonymous authentication as well as show examples of how to implement email and password login manually should you have a need for it. In my opinion, Firebase has become too good to be ignored by any mobile app developer and understanding Firebase Authentication is important to understanding the other Firebase products such as Firebase Realtime Database etc.

Source Code

The source code for this tutorial can be found in this Github repository. You must add your own google-services.json file before the app will work. You do this by connecting your Firebase Project to the Android Studio project, I included a video to this in this post. If you want the Facebook login to work, you will also need to follow the tutorial to create a Facebook app and connect to the app. Finally, you should enable the login methods that you want to implement in Firebase console before they can work.


Also published on Medium.

About the Author valokafor

I am a Software Engineer with expertise in Android Development. I am available for Android development projects.

follow me on:
4 comments

Comments are closed