DEV Community

Cover image for Facebook Authentication with Firebase in React Native (Android)
Balogh Botond
Balogh Botond

Posted on • Updated on

Facebook Authentication with Firebase in React Native (Android)

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

Table of Contents

  1. Prerequisites
  2. Introduction
  3. Installing the Facebook SDK
  4. Configuring Firebase
  5. Configuring Facebook
  6. Facebook SDK Configuration
  7. Coding the Authentication Process
  8. Logging Out
  9. Conclusion

Prerequisites

To follow this guide, you should have:

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


Enter fullscreen mode Exit fullscreen mode

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.

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 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.
  2. Create a New App: Go to Facebook 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
  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 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.



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


Enter fullscreen mode Exit fullscreen mode

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



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


Enter fullscreen mode Exit fullscreen mode

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.



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


Enter fullscreen mode Exit fullscreen mode

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.



<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>


Enter fullscreen mode Exit fullscreen mode

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. 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:



   npm install @react-native-firebase/app
   npm install @react-native-firebase/auth


Enter fullscreen mode Exit fullscreen mode

Create firebase.js:
In your project root, create a file named firebase.js:



   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);
   }


Enter fullscreen mode Exit fullscreen mode

Configure Build Settings:
In build.gradle (app), add:



   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'
   }


Enter fullscreen mode Exit fullscreen mode

Register App with Firebase:
Follow the steps to register your app with Firebase:
Firebase App Registration Guide

Create Facebook Login Button:
Create a custom component FacebookLoginButton:



   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;


Enter fullscreen mode Exit fullscreen mode

Add FacebookLoginButton to the Login page.



import FacebookLoginButton from '../components/FacebookLoginButton';

...
  return (
    <View>
      ...
      <FacebookLoginButton />
    </View>
  );


Enter fullscreen mode Exit fullscreen mode

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

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::



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);
  });
};


Enter fullscreen mode Exit fullscreen mode

Login page
Log in by Facebook

Facebook authentication in Hungarian
FB authentication in Hungarian

The user is logged in by Facebook.
Logged in by Facebook

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.
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.
More about the author at LUNitECH

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

Top comments (0)