Facebook Authentication with Firebase in React Native (Android)
Tags: reactnative, firebase, android, tutorial
Published: 2024-01-17 12:36:45

This guide provides a comprehensive walkthrough for integrating Facebook Login with Firebase in an Android React Native application.

## Table of Contents

1. [Prerequisites](#prerequisites)
2. [Introduction](#introduction)
3. [Installing the Facebook SDK](#installing-the-facebook-sdk)
4. [Configuring Firebase](#configuring-firebase)
5. [Configuring Facebook](#configuring-facebook)
6. [Facebook SDK Configuration](#facebook-sdk-configuration)
7. [Coding the Authentication Process](#coding-the-authentication-process)
8. [Logging Out](#logging-out)
9. [Conclusion](#conclusion)

## Prerequisites

To follow this guide, you should have:
- Basic knowledge of React and React Native
- [A React Native environment set up](https://github.com/Balogh08/CodePlayground/tree/facebook_native_auth_android)
- Firebase project and Facebook Developer account

## Introduction

Facebook Login integration provides a convenient and secure way for users to log into your app. It not only streamlines the user experience but also leverages the robust security infrastructure of Facebook. This guide will help you set it up step-by-step.

## Installing the Facebook SDK

To integrate Facebook authentication in your React Native application, the first step is to install the Facebook SDK. This SDK provides the necessary tools and functions to facilitate Facebook Login in your app. To install the SDK, run the following command in your project's root directory:

```
npm install react-native-fbsdk-next
```

It is a React Native wrapper around the Facebook SDK. It simplifies integrating Facebook services into your application. After installation, you can use the various functionalities provided by the SDK, including `Facebook Login`.

For more details about this package [check the npm site.](https://www.npmjs.com/package/react-native-fbsdk-next)

## Configuring Firebase

To enable Facebook authentication in your React Native application, you need to configure your Firebase project to support Facebook login. Follow these steps:

1. **Go to the Firebase Console**: Navigate to the [Firebase Console](https://console.firebase.google.com/) and select your project.
2. **Access Authentication Settings**: From the Firebase project dashboard, go to `Authentication` > `Sign-in method`.
3. **Add New Provider**: Click on `Add new provider` and select `Facebook` from the list of available providers.
4. **Enable Facebook Authentication**: Enable Facebook as a sign-in provider and input the `App ID` and `App Secret`.
   - The App ID and App Secret are obtained from your Facebook Developer account, associated with the Facebook app you've set up for authentication. See the next step!

## Configuring Facebook

For integrating Facebook Login, you need to set up an app in your Facebook Developer account. Follow these guidelines:

1. **Create a Facebook Developer Account**: If you don't have one already, create a Facebook Developer account at [Facebook Developers](https://developers.facebook.com/).
2. **Create a New App**: Go to [Facebook Apps](https://developers.facebook.com/apps), and create a new app. Select the appropriate use case, typically `Authenticate and request data from users with Facebook`.
3. **Configure Your App**: Copy and paste the `App Id`, and `App Secret` to the Firebase console as mentioned in the `Configuring Firebase` part and copy and paste the `OAuth Redirect URIs` to the Facebook dashboard.
   - Find the **App ID** in the top right corner of the dashboard.
   - Obtain the **App Secret** from `App Settings > Basic`.
   - Configure **OAuth Redirect URIs** in the `Facebook Login` settings under `Use cases > Customize > Settings`.
You can add the necessary `permission` at the `Use cases > Customize` like `email` or `user profile`. It depends on the need of your application to know what permissions to request.![Permission joke](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bekdnf55fzn4jqqv139m.jpeg)

4. **Save the Changes**: save changes on both platforms, Facebook and Firebase.


## Facebook SDK Configuration

This section of the guide will walk you through the necessary steps to update your [Facebook SDK Configuration](https://developers.facebook.com/docs/facebook-login/android/) effectively.

Steps 1,3,4,5,6 needed to be taken. Step 2 is managed by the `react-native-fbsdk-next` node package and the rest is not related to this. Step 7 allows the user to log into the app by pressing a push notification which is not relevant now.

**Step 1: Select an app or create a new app**
By now you should have the app in the Facebook dashboard, so just select the one in which you want to implement Facebook authentication.

**Step 3: Integrate the Facebook SDK**

Updating `build.gradle` (Project Level)
It's essential to make sure your project's `build.gradle` file includes `mavenCentral()` in the repositories section. This is usually included by default, but it's always good to check.

```gradle
buildscript {
    repositories {
        // other repositories
        mavenCentral() // Ensure this is included
    }
    // rest of the buildscript
}
```

Updating `build.gradle` (Module: app)
Next, you need to add the Facebook login dependency to your app module's `build.gradle` file.

```gradle
dependencies {
    // other dependencies
    implementation 'com.facebook.android:facebook-login:latest.release'
}
```

**Step 4: Edit Your Resources and Manifest**
Update your `strings.xml` file with the necessary Facebook credentials. These are crucial for the SDK to function correctly. If facebookAppId is `12345` then the fbLoginProtocolScheme is `fb12345`.

```xml
<string name="facebook_app_id">yourFacebookAppId</string>
<string name="fb_login_protocol_scheme">fbYourFacebookAppId</string>
<string name="facebook_client_token">yourFacebookClientToken</string>
```

The `AndroidManifest.xml` requires internet permission and specific meta-data about ApplicationId and ClientToken for Facebook integration. Finally, add the specific `activities` as provided in the example.

```xml
<uses-permission android:name="android.permission.INTERNET"/>

<application android:label="@string/app_name" ...>
    <!-- other meta-data -->
    <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
    <meta-data android:name="com.facebook.sdk.ClientToken" android:value="@string/facebook_client_token"/>
    <!-- other activities -->
    <activity android:name="com.facebook.FacebookActivity"
        android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:label="@string/app_name" />
    <activity
        android:name="com.facebook.CustomTabActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="@string/fb_login_protocol_scheme" />
        </intent-filter>
    </activity>
</application>
```

**Step 5: Associate Your Package Name and Default Class with Your App**
React Native doesn't include the package name in the default `AndroidManifest.xml`. However, you can find it in the `build.gradle(app)` file as `applicationId "com.codeplayground"`. For the Default Activity Class Name, use `thepackagename.MainActivity`. You'll find the `MainActivity` file at `android/app/src/main/java/com/yourAppName/MainActivity.kt`, but no further action is required with this file for now.

**Step 6: Provide Development and Release Key Hashes for Your App**
Generating key hashes for your app. Follow the detailed instructions provided in the [Facebook documentation](https://developers.facebook.com/docs/facebook-login/android/#:~:text=Save-,6.%20Provide%20the%20Development%20and%20Release%20Key%20Hashes%20for%20Your%20App,-To%20ensure%20the). Once you have created the hashes, paste them into the `Key Hashes` field in your Facebook Developer account and save the changes.

## Coding the Authentication Process

To set up the authentication process, follow these steps:

**Install React Native Firebase SDK:**
   ```bash
   npm install @react-native-firebase/app
   npm install @react-native-firebase/auth
   ```

**Create `firebase.js`:**
   In your project root, create a file named `firebase.js`:
   ```javascript
   import firebase from '@react-native-firebase/app';

   // Basic Firebase configuration
   const firebaseConfig = {
     apiKey: process.env.API_KEY,
     authDomain: process.env.AUTH_DOMAIN,
     projectId: process.env.PROJECT_ID,
     storageBucket: process.env.STORAGE_BUCKET,
     messagingSenderId: process.env.MESSAGING_SENDER_ID,
     appId: process.env.APP_ID,
     measurementId: process.env.MEASUREMENT_ID
   };

   // Initialize Firebase
   if (!firebase.apps.length) {
       await firebase.initializeApp(firebaseConfig);
   }
   ```

**Configure Build Settings:**
   In `build.gradle (app)`, add:
   ```gradle
   apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"

   defaultConfig {
       // ...
       resValue "string", "facebook_app_id", project.env.get("FACEBOOK_APP_ID")
       resValue "string", "fb_login_protocol_scheme", project.env.get("FB_LOGIN_PROTOCOL_SCHEME")
       resValue "string", "facebook_client_token", project.env.get("FACEBOOK_CLIENT_TOKEN")
   }

   dependencies {
       // ...
       implementation 'com.facebook.android:facebook-login:latest.release'
   }
   ```

**Register App with Firebase:**
   Follow the steps to register your app with Firebase:
   [Firebase App Registration Guide](https://firebase.google.com/docs/android/setup#register-app)

**Create Facebook Login Button:**
   Create a custom component `FacebookLoginButton`:
   ```javascript
   import React from 'react';
import { LoginButton, AccessToken } from 'react-native-fbsdk-next';
import auth from '@react-native-firebase/auth';
import { useNavigation } from '@react-navigation/native';

const FacebookLoginButton = () => {
  const navigation = useNavigation();

  const handleFacebookLogin = async () => {
    try {
        // Once signed in, get the user AccessToken
        const data = await AccessToken.getCurrentAccessToken();

        if (!data) {
            throw 'Something went wrong obtaining access token';
        }

        // Create a Firebase credential with the AccessToken
        const facebookCredential = auth.FacebookAuthProvider.credential(data.accessToken);
        const userCredential = await auth().signInWithCredential(facebookCredential);
        console.log('User signed in with Facebook!', userCredential.user);
        navigation.navigate('Home');
    } catch (error) {
        console.log('Facebook login or Firebase credential failed:', error);
    }
  };

  return (
    <LoginButton
      onLoginFinished={handleFacebookLogin}
      onLogoutFinished={() => console.log("logout.")}/>
  );
};

export default FacebookLoginButton;
   ```

Add FacebookLoginButton to the Login page.
```
import FacebookLoginButton from '../components/FacebookLoginButton';

...
  return (
    <View>
      ...
      <FacebookLoginButton />
    </View>
  );
```
Start your application on your device or simulator and try it out. Pressing the Facebook button should navigate to Facebook authentication and back after successful authentication. It is up to you how to handle the successful login. In my case, the app navigates to the `Home.js`, but to improve a `useLayoutEffect` could be used for more smooth animation.
   Source: [Firebase Authentication with Social Providers](https://rnfirebase.io/auth/social-auth)

## Logging Out
After logging in you want the user to be able to log out as well. Besides logging out the user by the Firebase `signOut` function, also Facebook logout must be implemented by the `LoginManager`::

```javascript
import auth from '@react-native-firebase/auth';
import { LoginManager } from 'react-native-fbsdk-next';

const handleLogout = () => {
  auth().signOut().then(() => {
    // Log out from Facebook
    LoginManager.logOut();
  }).catch((error) => {
    Alert.alert('Logout Failed', error.message);
  });
};
```

Login page
![Log in by Facebook](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/85ry6bo29mhizvs5l158.png)

Facebook authentication in Hungarian
![FB authentication in Hungarian](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5co1gjp072h96vjk4ynd.png)

The user is logged in by Facebook.
![Logged in by Facebook](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f56pu8czya2uc8yvsu3g.png)

## Conclusion

By following these steps, users can seamlessly log in and log out using Facebook in your React Native Android application. In the Facebook developer dashboard, you can customize what information to ask for from the user while logging in with Facebook.

**Check out the final code** [here](https://github.com/Balogh08/CodePlayground/tree/facebook_native_auth_android).
The `IOS` version is coming soon. Let me know your thoughts on this article. Which third party do you prefer for authentication?

Thank you for reading.

<small>The article was written with the help of existing documentation, ChatGPT, Grammarly, and other human beings.</small>