How to add Firebase Authentication into your Android App, using FirebaseUI
In many apps these days authentication is crucial to making sure every one of your users has a unique and personal experience. Using Authentication allows users to create an account with your app to save their personal information, upload information to the cloud and access information personalized to only them. There are various ways to add authentication into your Android app, but one of the easiest ways is using FirebaseUI. FirebaseUI allows you to quickly add authentication functionality into your app from a variety of providers and takes care of most of the logic for you. In this article we’re going to explore how to add FirebaseUI Authentication into your Firebase connected Android app.
Alternatively if you just want the code, I created a sample app for this project that you can find on GitHub here:
Step 1
If you haven’t done so already you will need to create a project in Firebase and connect your Android app to that Firebase project. I wrote a tutorial that can guide you through that process which you can check out here:
Step 2
To get started we are going to add some dependencies to the app level build.gradle file. Navigate to that file and add this line under the dependencies:
implementation ‘com.firebaseui:firebase-ui-auth:5.1.0’
Then sync your gradle.
Note: If you plan to add sign-in using Facebook and/or Twitter this will require additional steps. You will need to add the Facebook and Twitter SDK dependencies and then navigatate to their respective websites to complete the set up there. For the purposes of this tutorial we won’t be using Facebook or Twitter but if you would like to I would recommend reading the Facebook: https://developers.facebook.com/docs/facebook-login/android and Twitter: https://developer.twitter.com/en/docs/basics/getting-started developer documentation for more information.
Step 3
Next you will need to decide which sign-in providers you want your app to support. You have the choice of allowing traditional sign-in using an Email/Password or a phone number. You also have the option of allowing third party sign-in through providers like Google, Microsoft, GitHub etc… These third party sign-in providers allow your users to easily sign into your application using accounts they already have, without having to remember long passwords. Lastly you also have the option to sign-in a user Anonymously, which we will discuss later.
To select which sign-in providers you wish to use navigate over to your Firebase console and select Authentication from the sidebar:
You should then see a list of providers to choose from:
For the purpose of this tutorial we will be using Email/Password, Phone, Google and Anonymous. These four distinct methods will allow us to get very familiar with FirebaseUI Authentication and allow you to see the pros and cons of each. Let’s go through each method and see how to enable them, as some require additional steps:
Email and Password:
This is the simplest and most traditional sign-in method on the list. We will simply enable this one, for now you can ignore enabling the passwordless option.
Phone
The phone sign-in implementation requires quite a bit more work. Upon enabling it you will see a message stating that “Phone Authentication requires additional configuration steps.”
To enable phone authentication you will have to find and set your app’s SHA-1 hash. This is necessary to allow Google to create an OAuth2 client and API key for your app (You can read this: https://developers.google.com/android/guides/client-auth for more info). In order to do this you will need to go through some steps:
First open your File Explorer and navigate over to:
C:\Users\%USERPROFILE%\.android
(Where %USERPROFILE% is your username on your PC).
Then open Command Prompt by Right-clicking on the Windows Start menu and selecting Command Prompt, or you can use ⊞ Win + R to open the run window and type cmd to launch Command Prompt that way. Next take the path you navigated to above and type this in cmd to navigate to that directory:
cd C:\Users\%USERPROFILE%\.android
(cd stands for Change Directory, in case you were curious).
Next you will have to enter this in cmd:
keytool -list -v -keystore debug.keystore
Upon entering this you will be asked for a password, the password is simply:
android
(Note: While typing the password you might notice that what you are typing isn’t showing up on screen or moving the cursor, this is normal! Just type the password and press enter)
If done correctly you should see a screen that looks like this:
Under Certificate Fingerprints you will see your SHA-1 hash. Highlight it and right click it to copy it. Then head back to Firebase and in the sidebar click the gear icon to go to your project settings:
Scroll down and under SHA Certificate Fingerprints click Add Fingerprint, paste the fingerprint you copied, and click save.
Phew! That was a lot, but now Phone authentication is properly set up. Before we continue however you should be aware of the security implications of using only a Phone Number to authenticate your users. As per the Firebase documentation (emphasis mine):
Security concerns
Authentication using only a phone number, while convenient, is less secure than the other available methods, because possession of a phone number can be easily transferred between users. Also, on devices with multiple user profiles, any user that can receive SMS messages can sign in to an account using the device’s phone number.
If you use phone number based sign-in in your app, you should offer it alongside more secure sign-in methods, and inform users of the security tradeoffs of using phone number sign-in.
So, hopefully that made you a bit more aware of the security implications.
Next we will activate Google Sign-in. Google sign-in also requires a SHA-1 hash. Luckily the SHA-1 hash we already configured above is project wide so we already completed that step! All you need to do is select a Project public-facing name and Project support email. The public-facing name is the name that will be shown to your users in emails sent by your app (Such as welcome emails you may send to your new users). The support email is what will be shown to users as they log in with their Google accounts through your app.
Anonymous
Finally that brings us to Anonymous authentication. Anonymous authentication is different in the sense that it’s technically not authenticating, as it doesn’t require a user to enter credentials. Anonymous auth is used as a way to allow a user to sign in as a guest. You can give the guest access to some parts of your app and if they wish to change to a permanent account later they can Upgrade by signing in with another auth method. Using FirebaseUI the upgrade process will be handled automatically and the users ID will remain the same, allowing them to access the same information they may have entered before. A common example of this is an e-commerce app. You might anonymously sign-in a user into your app, allow them to shop around and add items to their cart. Then, before they checkout you can prompt them to create an account. Upon creating an account the user will be returned to their cart, where the items they chose anonymously are still in the cart waiting to be bought. Anonymous auth doesn’t require any additional steps right now so you just have to enable it:
Step 4 - Coding
Alright! That was a lot but by now all the authentication options we selected are properly enabled in Firebase. The next step is to start coding and set up the FirebaseUI sign-in screen.
In your Activity you will first need to add this import statement:
import com.firebase.ui.auth.AuthUI;
Then we will create a method to show FirebaseUI and start by specifying a List of providers to show in the UI. Since we selected: Email/Password, Phone, Google and Anonymous, we will add these to the list. This is the syntax:
public void showFirebaseUI(){
List<AuthUI.IdpConfig> providers = Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.PhoneBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build(),
new AuthUI.IdpConfig.AnonymousBuilder().build());
Next we will have to use startActivityForResult to set the providers and build the UI:
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.build(), RC_SIGN_IN);
}
The second parameter, RC_SIGN_IN, can be any arbitrary number that you choose. It’s used to identify the sign-in request when the result is returned to your app in onActivityResult (which we will define next). RC_SIGN_IN should be declared as a constant above your onCreate method:
private static final int RC_SIGN_IN = 123;
startActivityForResult is also where you can customize the look of the UI. By default FirebaseUI uses the theme of your app. However, you can customize your own theme in the styles.xml file and pass that into the method above:
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.setTheme(R.style.AppTheme)
.build(), RC_SIGN_IN);
}
You can also add in your apps’ logo drawable, which will appear above the sign-in buttons. For now I’m just using a placeholder image:
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.setTheme(R.style.AppTheme)
.setLogo(R.drawable.baseline_android_black_36)
.build(), RC_SIGN_IN);
}
Finally you need to add this code above your onCreate method:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
and this inside your onCreate method:
if (user != null) {
// User is signed in
Intent homeIntent = new Intent(this, MainActivity.class);
startActivity(homeIntent);
} else {
// No user is signed in
showFirebaseUI();
}
This code checks if a user is currently signed in with Firebase in your app. If they are, the user is not null and you can handle where to send the user. If the user is null it means they are not signed in and we will send them to the FirebaseUI sign-in screen.
If you run the app now you should see something like this:
Pretty neat! FirebaseUI handles the button placement, logos and sizes for you. The buttons are all functional, however we need to implement onActivityResult first to send your newly signed in users to your home screen, get their info and so on.
This is the code for onActivityResult:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
Intent homeIntent = new Intent(this, MainActivity.class);
startActivity(homeIntent);
} else {
finish();
}
}
}
Let’s walk through that code above:
The first if statement:
if (requestCode == RC_SIGN_IN)
checks to see of the requestCode received from Firebase is equal to the RC_SIGN_IN constant we defined earlier. This should always return true, however, if you have another startActivityForResult somewhere else in your code you should make sure that the RC_SIGN_IN number you use there is different and unique. For example, we used 123 as our code, if you create another sign in page elsewhere in your code make sure to change that, perhaps to 456.
The second if:
if (resultCode == RESULT_OK)
will always return true if the first if statement passes. All this means is that the user is now signed in.
The code inside the nested ifs will be whatever you want to have happen when the user signs in. In most cases you will want to create an intent to send the user to your home screen, which is what we do here, but your own use cases might vary.
Finally there is the else statement:
else {
finish();
}
This will execute if the user cancels the sign in process, such as by clicking the back button. The best way to handle this scenario is to call finish(); to end the activity and send the user back out of your app.
Next Steps:
Congratulations! Most all the logic should be set up now. If you open the app and sign in with any method you should be sent to your Main Activity. You can also check to make sure you were logged in properly by checking the Users tab under Authentication in your Firebase console. From there you can also delete users and add new ones. Be sure to check out part 2 of this tutorial where we will show you how to handle more authentication logic such as: Signing out, Deleting an account and upgrading an Anonymous user to a permanent one: