Firebase

Firebase – Anonymous Authentication

Hello androiders, welcome to the sixth 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.
  • Part 5, Firebase Social Authentication, a type of authentication which authenticates a user with his social accounts.

In this part

In this article, we are going to discuss about anonymous authentication.
Anonymous Authentication, as the name suggests, allows any user to authenticate using a temporary anonymous account. What’s more ? You can access the data and the services provided by the application even if you don’t sign-up. Thereafter, if you feel that you want to convert your account into a permanent one, you can immediately link it to your credentials. That’s it !!!!
Secondly, whenever you will sign-in anonymously, Firebase will generate a new User ID every time.
Anonymous Authentication is very good for those users who don’t want to reveal their identity and authenticate to access the services and data provided by the application.

Getting started

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

  • Login a User Anonymously
  • Link an Anonymous Account to a Permanent Account
  • Logout a user
  • More In Firebase

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

Login a User Anonymously

The signInAnonymously method of FirebaseAuth let’s us to sign in anonymously. No need to pass any email and password. It’s that easy !!!!

The addOnCompleteListener is fired as soon as the process of signing in is completed. Thereafter, it returns the result in the form of a task of type AuthResult.

mFirebaseAuth.signInAnonymously().addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    // Authentication successful
                } else {
                   // Authentication failure
                }
            }
        });

 

After you sign in anonymously, you can see the respective user info in Firebase Console by going through the following steps:
If you have created a project on Firebase, you will be able to find Auth section in Firebase Console.
Next, go to the Users tab and you will be able to find the list of users who have logged-in in your app.

Link An Account

Firebase provides converting an anonymous account into a permanent one using the following options:

  • Link with Email and Password
  • Link with Google
  • Link with Facebook

This is one very interesting feature provided by Firebase. Guess what, you can easily convert your anonymous account into a permanent one without losing your previous data !! Isn’t it fantastic ??
Say for example, you wish to explore a game and started playing it without logging in. If you found the game interesting, you might want to login using any social account. So, after doing so, you start playing it again. Thereafter, you won’t get your previous points/achievements you received when you played before logging in.

Now, to solve this, you can simply implement Firebase Anonymous Authentication wherein you can sign-in anonymously and play as long as you want. Meanwhile, if you wish to login using a Facebook account, no need to worry, you can easily access your previous data in your newly linked account.

Note:You can convert your anonymous account into a permanent one only while you are logged in.

Link an Anonymous Account using Email and Password

Linking an anonymous account using email and password is very easy. Simply, get the email and password from the user and call getCredential method and assign it to the AuthCredential’s object.
Remember to use EmailAuthProvider for the same.


        AuthCredential credential = EmailAuthProvider.getCredential(email, password);

        convertToPermanent(credential);

Link an Anonymous Account using Facebook

In this, you need to pass the token you receive after successful Facebook login and pass it to
getCredential method and assign it to the AuthCredential’s object.
Remember to use FacebookAuthProvider for the same.


        AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());

        convertToPermanent(credential);

Link an Anonymous Account using Google

In this, you need to pass the token you receive after successful Google login and pass it to
getCredential method and assign it to the AuthCredential’s object.
Remember to use GoogleAuthProvider for the same.


        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);

        convertToPermanent(credential);

And, here is the common method for linking an anonymous account :


private void convertToPermanent(AuthCredential credential) {

        if (NetworkUtils.isInternetAvailable(this)) {

           mFirebaseAuth.getCurrentUser().linkWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    if (task.isSuccessful()) {
    
                        // Linked account successfully
                        // Do whatever you want
                    } else {
                        // Linking to account failed
                    }
                }
            });
        }
    }

As soon as the said process completes, the onComplete method is fired and it returns the particular task. If the task is successful, this means that you have successfully linked your account. Now onwards, you can access the account using the newly used credentials.

Logout a user

mFirebaseAuth.signOut();

 

More In Firebase

You can do a lot more things in Firebase. Here are some of them which can be performed using Firebase Console:

Verify Email Address

You can verify email address of the user and send a verification email by completing the following steps:

  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 Email Templates tab and go to Email address verification tab.

Email_Verification

You can change the Email Template according to your needs.

Reset Password

You can send an email to the user to reset his/her password by completing the following steps:

  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 Email Templates tab and go to Password reset verification tab.

Reset_Password

Change Email Address

You can change the email address of the user and send an email regarding the same by completing the following steps:

  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 Email Templates tab and go to Email address change verification tab.

Change_Email

After a user links his/her account, the already mentioned user details are updated with the new credentials in Firebase Console.
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 important and useful anonymous authentication is, in terms of applications.

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

Firebase Anonymous Authentication Demo

Hope you learnt a lot 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!
  • Abhi jani

    Nice Suraj Keep it up with outstanding posts 🙂