Firebase Anonymous Login on Android

What if an anonymous user wants to join up for your app? I know what you're thinking.

Firebase Anonymous Login

The sign-in credentials can be simply linked to the anonymous account.

Furthermore, you can effortlessly continue working in future sessions while maintaining total data security.

If you want to make an e-commerce app like Amazon, it'll come in handy.

If you've ever worked with the Firebase Database, you'll know that you can't access it without authentication unless you expose rules to the public, which is hazardous and not suggested by Firebase.

You folks debating whether or not it's feasible? Because the Firebase Authentication SDK is capable of delivering such a powerful function.

How to Login to Firebase Anonymously on Android

Step 1: Establishing a connection with Firebase AUTH

First and foremost, in order to complete this lesson, you must have an Android studio project.

Using Android Studio to Create a New App.

By going to File > New > New Project, you can start a new project.

Connect your app to the Firebase cloud platform.

After you've created your project, you'll need to add Firebase Auth to it.

Select Tools > Firebase from the drop-down menu. It will open a new window on the right side of your screen with a list of all the services supplied by Firebase.

Because you're just interested in Firebase Authentication, you'll select that option. Select Authentication -> Email and Password Authentication from the drop-down menu.

You must first connect to Firebase before adding the Firebase Authentication requirements to our Android app. Select Connect to Firebase from the drop-down menu.

If you are not connected in with your Google account, Android Studio will prompt you to do so.

You can start a new Firebase project or continue working on an existing one.

However, because I'm starting a new Firebase Project, I'll type in the project name, choose a country, and then click Connect to Firebase.

Add Dependencies for Firebase Authentication to Your Project

1) It's as easy as clicking the button that says "Add Firebase Authentication to your app."

2) After a short time, you should be able to see that all of the dependencies have been properly set up.

In the Firebase Console, enable Anonymous Authentication.

Log in to http://console.firebase.google.com/ with the same ID that you used to log in to Android Studio.

As you can see, our project was successfully added. Now simply click on it.
  • From the left pane, choose Authentication.
  • Toggle to the Sign-in Methods tab.
  • Toggle the button and select Anonymous.
  • Then press the Save button.
And the work on Firebase is finished. Now is the time to get inside Android Studio and start creating code.

Step 2 – Log in Anonymously

You'll need a button to start the procedure and a text view to keep the user informed about the status. There's even a button for later usage!

This is the interface we'll utilize to allow people to log in anonymously.

The first activity that will be executed when a user runs the programmed is MainActivity.java with activity main.xml layout files.

Here's how you do it (as seen above):
  • To show the output to the user, use a TextView.
  • When a background process is executing, the progress bar is displayed.
  • To add a trigger with the anonymous login, use the Login Anonymous Button.
  • Link Email Button: To begin a new activity in which we will ask for an email address and a password, and then link it to an existing account.

Below is the complete activity_main.xml code

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <TextView
        android:id="@+id/loginMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="You are logIn anonymously!"
        android:textSize="25sp"
        android:visibility="invisible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.392"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.35" />
 
    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="invisible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.462"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.459" />
 
    <Button
        android:id="@+id/loginAnonymousbutton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="384dp"
        android:text="Login Anonymous"
        android:textAllCaps="false"
        android:textSize="25sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
 
    <Button
        android:id="@+id/linkAccountButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="500dp"
        android:text="Link Email?"
        android:textAllCaps="false"
        android:textSize="25sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
</androidx.constraintlayout.widget.ConstraintLayout>

First, we must construct TextView and Buttons instances and initialise them using the tags that we previously specified in XML.

Then, just like with previous Firebase Authentications, we'll need an instance of FirebaseAuth and FirebaseUser to receive information about logged-in users; construct those in the onCreate() method.

//Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
//initialization
loginMessage = findViewById(R.id.loginMessage);
progressBar = findViewById(R.id.progressBar);
loginAnonymousbutton = findViewById(R.id.loginAnonymousbutton);
linkAccountButton = findViewById(R.id.linkAccountButton);

You must now execute a method named signInAnonymously on the FirebaseAuth instance that we generated earlier when the user selects the "Login in Anonymously" button.

However, you must first determine whether the user is already logged into the app.

Linking Anonymous Account with Email and Password

Remember the "Link Email" that was established in Main Activity? When a user clicks on it, this activity will begin.

Linking is actually fairly simple; all you have to do is ask the user for their email address and password, and then call the linkWithCredentials method to complete the process.

In the Firebase Console, enable the Email-Password Sign-In method.

In the Firebase Console, enable the Email-Password Sign-In method.

That is a critical task to complete (and the highly forgettable task too).

In Firebase Console, activate Sign-in using Email and Password, same as you did with Anonymous login. Here's how to do it:
  • Select the project where your app is stored in Firebase Console.
  • From the left pane, choose Authentication.
  • Toggle to the Sign-in Methods tab.
  • Toggle the toggle button for Email-Password.
  • Then press the Save button.

Getting details from User

As previously said, you must obtain the user's login and password.

You'll need to make an activity with LinkAccount.java and activity link account.xml for this.

When the user clicks the "Link Email" button in Main Activity, this activity will be launched.

Here's what you'll need to do:
  • EmailEditText: This is where the user's email is collected.
  • PasswordEditText: This is used to obtain the user's password.
  • The SignIn Button is used to sign the user in.
Below is the complete activity_link_account.xml code:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LinkAccount">
 
    <EditText
        android:id="@+id/email_id"
        android:layout_width="280dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="36dp"
        android:layout_marginTop="168dp"
        android:hint="Enter emial here"
        android:textSize="22sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <EditText
        android:id="@+id/password"
        android:layout_width="280dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="36dp"
        android:layout_marginTop="236dp"
        android:hint="*****"
        android:textSize="22sp"
        android:inputType="textPassword"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.505"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <Button
        android:id="@+id/signInButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="336dp"
        android:text="Sign IN"
        android:textAllCaps="false"
        android:textSize="25sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
</androidx.constraintlayout.widget.ConstraintLayout>

Initializing instances

Now is the time to link the anonymous account to the user's email address and password.

To get the user's input, create an instance of EditText and Button, same like before.

Then, as seen below, build a FirebaseUser object and initialise it using the current user:

//initialization
email = findViewById(R.id.email_id);
password = findViewById(R.id.password);
signInButton = findViewById(R.id.signInButton);
currentUser = FirebaseAuth.getInstance().getCurrentUser();

Creating an Anonymous account with an email address and a password

You must now verify that currentUser is not null.

Remember that you can only link an account that is already logged in anonymously.

Then, in the EmailAuthProvided class, there is a static function titled getCredential. Call that function and provide the email and password that we just got from the user.

This method returns an AuthCredential object, which you can use to link the account by executing the linkWithCredential method on the FirebaseUser class instance.

On linkWithCredential, you can additionally override the callback functions, which include the following:
  • addOnCompleteListener: This will also @override the method onComplete, which will check if the procedure is finished. If it's finished, you'll need to see if it worked or not.
  • addOnFailureListener: This will also @override a method called onFailure, which will check if the process has failed. The logcat window can then be used to display errors.

Post a Comment

Previous Post Next Post