Paul Trebilcox-Ruiz

Fire_2.png

As you may have guessed, the user creation and login processes can be complicated and cumbersome. Not only does each provider have its own unique caveats, but keeping track of Android device and authentication state is a beast in and of itself, as can be seen in the following flow chart.

When working with data in Firebase, there will be times when you will want to validate a user to ensure that they should be allowed to access the requested information. Luckily, Firebase provides an authentication framework which will allow you to log users into your app using a username and password, or one of the approved authentication providers, such as Google, Facebook, Twitter or GitHub.

image00-1.png

Luckily, the FirebaseUI library also includes an easy to implement component to handle creating users and authenticating. While you can authenticate with a username and password, this tutorial will focus on using the FirebaseUI library to create and authenticate a user through the Google authentication provider with Firebase. Once you are able to add a user to Firebase, you will learn how to work with the FirebaseUser object.

Setting Up Authentication in Firebase

Before you begin, you will need to enable authentication in the Firebase console. Under the Auth section, select the Sign-In Method tab.

Sign-in_method.png

From here you should see a list of available sign-in providers.

Sign-in_providers.png

For this tutorial you will only need to select the Google provider. In the dialog window that opens, click on the toggle in the top right corner to enable the Google sign-in provider. Once this is done, click on the blue SAVE button.

SHA1_key.png

Now that you have enabled the Google sign-in provider, it's time to dive into your Android application. One thing to note is that the SHA1 key for your signing key must be registered with Firebase, as covered in the previous tutorial in this series.

Authenticating with the FirebaseUI Library

Under the dependencies node of your app module's build.gradle file, import the FirebaseUI auth library. Note that the version number will change as Firebase and the FirebaseUI library continue to be developed. The FirebaseUI auth library also imports the Firebase and Google Play Services libraries that are required for Firebase authentication, so you don't need to worry about those.


compile 'com.firebaseui:firebase-ui-auth:0.4.3'

Once you have imported the library, you will need to create an Activity to handle authentication. For this tutorial I will simply use the app's MainActivity class. When you want users to sign into your app, you will need to get a reference to the FirebaseAuth object. If the FirebaseAuth getCurrentUser() method returns a user, then the user is already signed in. If no user is associated with the FirebaseAuth object, then you can start the FirebaseUI's sign-in Activity with a list of sign-in providers that your app supports.


private void handleAuthentication() {
   FirebaseAuth auth = FirebaseAuth.getInstance();
   if (auth.getCurrentUser() != null) {
       //User is signed in already. You're good to go!
   } else {
       startActivityForResult(
               AuthUI.getInstance()
                       .createSignInIntentBuilder()
                       .setProviders(AuthUI.GOOGLE_PROVIDER)
                       .build(),
               SIGN_IN_REQUEST_CODE);
 
   }
}

The above method will display a list of buttons representing the supported sign-in providers. Although I am not covering it here, there are also options to configure the UI and make the component mesh well with your app's theme.

image07.png

When the user selects the Sign in with Google button, they will either begin to authenticate if they only have one Google account associated with their device, or they will be presented with an account selector dialog.

Accounts.png

Once the user has selected an account, the FirebaseUI library will handle working with the rest of the Google sign-in provider to authenticate the user with your Firebase backend. When the process has completed, onActivityResult will be called and you can validate if the process was successful or not.


protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   if (requestCode == SIGN_IN_REQUEST_CODE) {
       if (resultCode == RESULT_OK) {
           Toast.makeText(this, "User signed in!", Toast.LENGTH_SHORT).show();
       } else {
           // Something didn't work out. Let the user know and wait for them to sign in again
       }
   }
}

Now that your user has signed in, you should be able to see their account in the Auth section of the Firebase console under the Users tab.

image04.png

Getting User Profile Information

At this point you may be thinking, "OK, my user has authenticated with Firebase, so what?" While it may not seem like much, you can now access the user account to display information for your user and keep track of data based on their unique ID. This means if you have user specific information, such as submitted posts or chat entries, you have a way of adding it to Firebase and ensuring that only certain users have access to it. You can access this information by grabbing the current FirebaseUser object from FirebaseAuth and calling the appropriate methods for the data you need.


private void displayUser() {
   FirebaseAuth auth = FirebaseAuth.getInstance();
   if (auth.getCurrentUser() != null) {
       FirebaseUser user = auth.getCurrentUser();
       Glide.with(this).load(user.getPhotoUrl().toString()).into(mProfileImage);
       mProfileDisplayName.setText(user.getDisplayName());
       mProfileUid.setText(user.getUid());
       mProfileEmail.setText(user.getEmail());
   }
}

 The above code will simply display the information obtained about the current user.

user_info.png

While this example is very simple, it does show you how to grab your user's information so that you can use it in other parts of the app, such as creating a unique node for that user in your Firebase Real-time Database JSON tree.

Updating User Information

There will be times where users will want to update their information for their user account, such as a change in their name or to update their profile image. This can be done easily enough by creating a UserProfileChangeRequest object with the new information that your user would like to use. You can then call updateProfile on the FirebaseUser object and add an OnCompleteListener to act on the results.


private void updateUserName() {
   FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
 
   UserProfileChangeRequest updates = new UserProfileChangeRequest.Builder()
           .setDisplayName("Paul is super awesome or something")
           .build();
 
   user.updateProfile(updates).addOnCompleteListener(this, new OnCompleteListener<Void>() {
       @Override
       public void onComplete(@NonNull Task<Void> task) {
           if( task.isSuccessful() ) {
               displayUser();
           }
       }
   });
}

 This code will change the display name for the authenticated user and then show it on the screen.

image01-1.pngFinishing Up

While this tutorial has just touched the basics of authentication, you should now be able to implement enough to get your own apps up and running with user accounts. The authentication library in Firebase includes many more features that may be useful for your app, such as the ability to change/reset passwords, delete accounts, authentication against multiple providers for one account and anonymous login for users.

Paul_Trebilcox-Ruiz.jpgPaul Trebilcox-Ruiz

Paul is an Android developer out of Denver, Colorado. He currently works for Tack Mobile, a contracting company specialized in mobile apps and connected devices. Paul has created various Android tutorials and video courses over the past three years, with his most recent work through Envato Tuts+, and he has recently published a book on Android TV development. Before becoming a developer, Paul worked as a zookeeper in his hometown of Fresno, California, so he may be able to answer your questions about giraffes :)

Related Search Term(s): Firebase

Create, Design, Develop and Connect at AnDevCon D.C. 2017!

Thoughts? Leave a comment: