Firebase AUTH for Android Facebook Login (Tutorial)

Do you want to learn how to use Firebase to validate your Facebook login?

You've arrived to the right location.

Android Facebook Login

As you may be aware, authentication is critical nowadays; you must always ensure that a real person, not a bot or a script, is entering into your app and generating the content.

Aside from that, you must provide each user with a tailored and familiar experience. As a result, you must first identify them.

Furthermore, Firebase includes an easy-to-use SDK and ready-to-use UI libraries that you can employ to provide your app users the greatest possible experience.

Its SDK alone offers a variety of signup/login alternatives. Email and password, phone number, or any other federated identity provider, such as Facebook and Twitter, are all examples.

To authenticate the user, we'll utilize Firebase to construct a federated identity provider. Or, to put it another way, we'll be signing up for Android using Facebook.

Users who have already signed up for Facebook may now log in to your app with a single button push! It's amazing how seamless it is.

I'll share and explain the entire code here, and the complete project can be found in this repository.

Structure of the Android Facebook Login with Firebase Tutorial

In order to sign up users using their Facebook profiles, we'll need to employ two SDKs:
  1. SDK for Firebase Authentication
  2. SDK for Facebook Login
We'll start by registering our app with Facebook, and then use their Facebook Login SDK as directed in their instructions.

We'll utilise that token to authenticate our users to Firebase after they've logged in with Facebook.

Believe me when I say that it's a lot easier than it appears.

Connecting Firebase to Your Project

If you're working with Firebase, it's self-evident that you'll need to link your project to Firebase.

Here's how you can do it with the Firebase Plugin, which is already included in Android Studio:

Step 1 - In Android Studio, create an Android project.

Step 2 - Select “Firebase” from the Tools menu.

Step 3 - It will bring up a right-hand assistant pane. There, look for Authentication.

Step 4 - From the Authentication drop-down option, choose "Email and Password Authentication." You should now see a "Connect to Firebase" button, which you should click.

Step 5 - Android Studio will now connect to Firebase and, if you haven't done so already, will prompt you to check in to your Google account. After that, you'll be asked to select an existing Firebase Project or create a new one. Accept the modifications with anybody you choose.

Step 6 - Now that your project is connected to Firebase, let's add Firebase Authentication to our app. Next to the "Connect to Firebase" button (which should be set to "Connected" by now), there will be another button labelled "Add Firebase Authentication to your App." Accept the adjustments from the new dialogue by clicking that.

The Firebase AUTH SDK has been successfully built, and your project is now connected to Firebase. Let's get started with adding the Facebook SDK to our Android app.

Installing the Facebook Login SDK in an Android App

1. Click "Create an app" on developer.facebook.com.

2. Fill in the fields "App Name" and "Contact Email."

3. You'll see a list of Facebook products; select "Facebook Login" and click "Set up."

4. Follow the documentation instructions:
  • 4.1 Get the most recent Facebook SDK for Android.
  • 4.2 Make your build Facebook-dependent. And sync the project with gradle (Module: app).
  • 4.3 Tell us the name of your app package and activity class.
  • 4.4 Include your key hash development and distribution. Simply copy the code for the operating system you're running and paste it into Android Studio's Terminal. You'll be given a 28-character long string key to copy and paste into the Facebook developers page, then save and continue.
  • 4.5 Single Sign-On should be enabled for your app.
  • 4.6 Make the necessary changes to your resources and manifest according to the instructions.
  • 4.7 We're not interested in logging app events to Facebook Console, thus remove the log app event option. If that's the case, you can follow the instructions there. Our app is now securely linked to the Facebook Login SDK. Now is the time to put the functionality into place.
5. Add the Facebook Login Button to your website. This is the code for the classic blue button with the Facebook logo and the words "Continue with Facebook." Simply copy and paste the following code into activity main.xml:

<com.facebook.login.widget.LoginButton
    android:id="@+id/login_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="30dp"
    android:layout_marginBottom="30dp" /> 

6. Now we'll implement the functionality of this button, but first, let's construct a CallBackManager instance. Which handles the authentication process' callbacks, such as whether the authentication was successful or not.

CallbackManager mCallbackManager = CallbackManager.Factory.create();

7. Let's implement the Login Button's click event and handle the callbacks. Remember that, aside from information that is publicly available, we must inform Facebook about the data we intend to read from the user profile.

LoginButton loginButton = findViewById(R.id.login_button);

//Obtaining the necessary permissions to read
loginButton.setReadPermissions("public_profile","email", "user_birthday", "user_friends");

//Registering callback.
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        //Sign in has been completed.
        Log.i(TAG, "onSuccess: logged in successfully");

        //Obtaining information about the user
        GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(JSONObject object, GraphResponse response) {
                //Code for the application
                Log.i(TAG, "onCompleted: response: " + response.toString());
                try {
                    String email = object.getString("email");
                    String birthday = object.getString("birthday");

                    Log.i(TAG, "onCompleted: Email: " + email);
                    Log.i(TAG, "onCompleted: Birthday: " + birthday);

                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.i(TAG, "onCompleted: JSON exception");
                }
            }
        });

        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,email,gender,birthday");
        request.setParameters(parameters);
        request.executeAsync();

    }

    @Override
    public void onCancel() {
        Log.d(TAG, "facebook:onCancel");
    }

    @Override
    public void onError(FacebookException error) {
        Log.d(TAG, "facebook:onError", error);
    }
});

}

Our software integrates seamlessly with Facebook Signup. Now we must also implement it for Firebase.

Using Firebase to Complete Facebook Authentication

Let's fine-tune the Firebase Authentication using the Firebase Console before we start developing it.

In Firebase Authentication, we need to enable Facebook under Sign-on providers in the Sign-in methods tab.

When you enable it, though, it will prompt you for an App ID and App secret, as well as an OAuth redirect URL.

These can be found in the Facebook Console. Choose an app. Expand the settings option on the left side and click "Basic," where you'll find both the App ID and App Secret. Copies should be pasted into Firebase Console.

Let's finish off by adding the OAuth redirect URI to your Facebook app's settings.

Go to your Facebook Console and paste that URL.

Expand Facebook Login and select settings on the left side, under product. On the right hand side, you'll find the Client OAuth Settings. Also, providing a valid OAuth Redirect URI will be an option. It's as simple as that.

That is all there is to it. Now go to the Firebase Console and activate Facebook, and we're ready to start creating Firebase Code.

We already had our Android app connected to Firebase and the Firebase Authentication Libraries deployed.

Now is the time to put the functionality in place.

Create and initialize a Firebase AUTH object first:

FirebaseAuth mFirebaseAuth = FirebaseAuth.getInstance();

We need to check whether someone is signed in or not when the app is launched so that we may take appropriate action:

@Override
public void onStart() 
{
  super.onStart();
  //Check if the user is logged in (non-null) and adjust the user interface accordingly.
  FirebaseUser currentUser = mFirebaseAuth.getCurrentUser();
  if (currentUser != null) {
      Log.i(TAG, "onStart: Someone logged in <3");
  } else {
      Log.i(TAG, "onStart: No one logged in :/");
  }
}

Remember the onSuccess callback method, which is invoked when a Facebook signup is successful? We'll need to extract credentials from that token and pass them to Firebase Auth.

The entire procedure is as follows:

private void handleFacebookAccessToken(AccessToken token) 
{
Log.d(TAG, "handleFacebookAccessToken:" + 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()) {
            //After a successful sign-in, update the user's information in the UI.
            Log.d(TAG, "signInWithCredential:success");
            FirebaseUser user = mFirebaseAuth.getCurrentUser();
            Log.i(TAG, "onComplete: user's login has been completed:" + user);

        } else {
            //Display a message to the user if they are unable to sign in.
            Log.w(TAG, "signInWithCredential:failure", task.getException());
            Toast.makeText(MainActivity.this, "Authentication failed.",
                    Toast.LENGTH_SHORT).show();
        }
    }
});
}

Simply call that method as follows in the onSuccess callback function:

//processing the Firebase Auth token
handleFacebookAccessToken(loginResult.getAccessToken());

That is all there is to it. The whole code for MainActivity.java is as follows:

package com.androidbull.learnfirebaseauthu;
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.Profile;
import com.facebook.login.LoginResult;
import com.facebook.GraphResponse;
import com.facebook.login.widget.LoginButton;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FacebookAuthProvider;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.firebase.auth.FirebaseUser;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.FirebaseAuth;
 
import org.json.JSONObject;
import org.json.JSONException;

import java.util.Arrays;
 
public class MainActivity extends AppCompatActivity 
{
    private CallbackManager mCallbackManager;
    private FirebaseAuth mFirebaseAuth;
    private static final String TAG = "MainActivity";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) 
{
    setContentView(R.layout.activity_main);
        mFirebaseAuth = FirebaseAuth.getInstance();
        super.onCreate(savedInstanceState);

        mCallbackManager = CallbackManager.Factory.create();
 
        LoginButton loginButton = findViewById(R.id.login_button);
 
        //Obtaining the necessary permissions to read
        loginButton.setReadPermissions("public_profile","email", "user_birthday");
 
        //Creating a callback
        loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) 
{
                //Sign in has been completed.
                Log.i(TAG, "onSuccess: logged in successfully");
 
                //processing the Firebase Auth token
                handleFacebookAccessToken(loginResult.getAccessToken());
 
                //Obtaining information about the user
                GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() 
{
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) 
{
                        //Code for the application
                        Log.i(TAG, "onCompleted: response: " + response.toString());
                        try 
{
                            String email = object.getString("email");
                            String birthday = object.getString("birthday");
                            Log.i(TAG, "onCompleted: Email: " + email);
                            Log.i(TAG, "onCompleted: Birthday: " + birthday);
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.i(TAG, "onCompleted: JSON exception");
                        }
                    }
                });
 
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,gender,birthday");
                request.setParameters(parameters);
                request.executeAsync();
            }
 
            @Override
            public void onCancel() {
                Log.d(TAG, "facebook:onCancel");
            }
 
            @Override
            public void onError(FacebookException error) {
                Log.d(TAG, "facebook:onError", error);
            }
        });
 
    }
 
    private void handleFacebookAccessToken(AccessToken token) {
        Log.d(TAG, "handleFacebookAccessToken:" + 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()) {
                            //After a successful sign-in, update the user's information in the UI.
                            Log.d(TAG, "signInWithCredential:success");
                            FirebaseUser user = mFirebaseAuth.getCurrentUser();
                            Log.i(TAG, "onComplete: login completed with user: " + user.getDisplayName());
 
                        } else {
                            //Display a message to the user if they are unable to sign in.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Toast.makeText(MainActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
 
    @Override
    protected void onActivityResult(int requestCode1, int resultCode1, @Nullable Intent data) {
        mCallbackManager.onActivityResult(requestCode, resultCode1, data);
        super.onActivityResult(requestCode1, resultCode1, data);
    }
 
    @Override
    public void onStart() {
        super.onStart();
        //Check if the user is logged in (non-null) and adjust the user interface accordingly.
        FirebaseUser currentUser = mFirebaseAuth.getCurrentUser();
        if (currentUser != null) 
{
            Log.i(TAG, "onStart: Someone logged in <3");
        } else {
            Log.i(TAG, "onStart: No one logged in :/");
        }
    }
}

Post a Comment

Previous Post Next Post