Firebase

Firebase – Social Authentication

Hello droiders, welcome to the fifth 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.
  • Part 4, Firebase – Basic Authentication, a type of authentication which authenticates a user with his email and password.

In this part

In this article, we are going to discuss about federated identity provider authentication.
Federated identity provider integration is nothing but allowing users to authenticate their identity using either Google, Facebook or Twitter. Many a times, it takes time to sign-up or sign-in using any social networking apps, but after authenticating through Firebase, you won’t be able to say that. Through this type of authentication, Firebase manages the tokens and all personal data of the user’s respective social accounts.

After using it in your application, you will definitely suggest it to others to use the same.

Getting started

In this post, we are going to create a demo that will perform following operations:

  • Authenticate through Google
  • Authenticate through Facebook
  • Authenticate through Twitter

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.0.2'
    
  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.
            }
            // ...
        }
    };
    // ...
}

Authenticate Using Google

As you will have to sign in using Google, you will have to go through all the steps required to integrate Google in your app. If you haven’t done so, follow the steps specified in Enable Google Integration In Android.

Before authenticating from your Google account using Firebase, it is necessary to complete the following steps to enable Google Sign-In in Firebase:

  1. If you have created a project on Firebase, you will be able to find Auth section in Firebase Console.
  2. On the Sign in method tab, enable the Google sign-in method and click Save.

enable_google_sign_in

 

Now, let’s look how to authenticate the user on successful Google login:

private void firebaseAuthWithGoogle(final GoogleSignInAccount acct) {

   AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
   mAuth.signInWithCredential(credential)
           .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
               @Override
               public void onComplete(@NonNull Task<AuthResult> task) {
                   if (!task.isSuccessful()) {
                       // Handle authentication failure
                   } else {
     // Do whatever you want on successful authentication
                   }
               }
           });
}

 

Authenticate Using Facebook

We can also let the users use their Facebook account to authenticate with Firebase.
As you will have to sign in using Facebook, you will have to go through all the steps required to integrate Facebook in your app. If you haven’t done so, go to Facebook For Developers. Go through everything and finally you will get an App ID and App Secret from it.

Before authenticating from your Facebook account using Firebase, it is necessary to complete the following steps to enable Facebook Sign-In in Firebase:

  1. If you have created a project on Firebase, you will be able to find Auth section in Firebase Console.
  2. Next, go to the Sign in method tab, enable the Facebook sign-in method and specify the App ID and App Secret you got from Facebook.
  3. Finally, see to it that your OAuth redirect URI is mentioned as one of your OAuth redirect URIs in your Facebook app’s settings page on the Facebook for Developers site in the Product Settings > Facebook Login config.

Facebook_enable_sign_in

Now, let’s look how to authenticate the user on successful Facebook login:



private void firebaseAuthWithFacebook(final AccessToken token) {
   AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
   mFirebaseAuth.signInWithCredential(credential)
           .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
               @Override
               public void onComplete(@NonNull Task<AuthResult> task) {

                   if (!task.isSuccessful()) {
                       // Handle authentication failure
                   } else {
                       // Do whatever you want on successful authentication
                   }
               }
           });
}}

 

Authenticate Using Twitter

We can also let the users use their Twitter account to authenticate with Firebase.
As you will have to sign in using Twitter, you will have to go through all the steps required to integrate Twitter in your app. If you haven’t done so, follow the steps specified in Twitter For Developers.

Before authenticating from your Twitter account using Firebase, it is necessary to complete the following steps to enable Twitter Sign-In in Firebase:

  1. If you have created a project on Firebase, you will be able to find Auth section in Firebase Console.
  2. Next, go to the Sign in method tab, enable the Twitter sign-in method and specify the API Key and API Secret you got from Twitter.
  3. Finally, see to it that your OAuth redirect URI is mentioned as Callback URL in your app’s settings page on your Twitter app’s config.

Twitter_enable_sign_in

First of all, set up the code to sign in to Twitter and you will get the respective token from the session.
Now, let’s look how to authenticate the user on successful Twitter login:



private void firebaseAuthWithTwitter(final TwitterSession session) {
   AuthCredential credential = TwitterAuthProvider.getCredential(
           session.getAuthToken().token,
           session.getAuthToken().secret);

   mAuth.signInWithCredential(credential)
           .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
               @Override
               public void onComplete(@NonNull Task<AuthResult> task) {
                  
                   if (!task.isSuccessful()) {
                       // Handle authentication failure
                    } else {
                       // Do whatever you want on successful authentication
                   }
               }
           });
}
}}

 

Signout from Firebase

You can signout from Firebase using the following :

FirebaseAuth.getInstance().signOut();

Manage Users

After a user signs up, a new user account is created and after signing in, linked to the credentials the user signed in with. This account is stored in your Firebase project.
In your apps, you can get to know the user’s basic profile information . In order to do so, go through Manage Users.

Conclusion

So, after going through this blog, you might have realised how easy and fast it is to authenticate using Firebase !!!!

Therefore, to implement Firebase Authentication in your app, take a look at the below link:

Firebase Social Authentication Demo

Hope you learnt something new from this article. But, it doesn’t end here. There is much more to Firebase and I hope that I can deliver more and more.

Suraj Makhija

Software Engineer(Android) at LetsNurture Infotech, a Passionate Android Explorer and a CR7 Fan

Want to work with us? We're hiring!
  • Soporboy Botirov

    Super! Thanks for great article!