How to Implement Facebook Login Using React Native Firebase?
Facebook OAuth is a powerful protocol that grants permission to log in with their Facebook account. It also powers the “Log in with Facebook” button in websites and apps everywhere.Here we will learn to implement Facebook Login using React Native Firebase.
Development Environment:
We will begin with the development environment. For this, you need to follow React Native CLI Quickstart instead of Expo CLI Quickstart.
![React Setup for Facebook login using react](https://latitudetechnolabs.com/wp-content/uploads/2022/02/Facebook-Reactenvionment-setup-768x379.png)
Started Code Cloning
To implement Facebook Login using React Native Firebase, you can refer to the GitHub Repository to Clone the starter code. Also from this, you can check the final code. Thus, the folder structure of the application will be like this.
![folder structure for facebook login using react](https://latitudetechnolabs.com/wp-content/uploads/2022/02/facebook-folder_structure-191x300.png)
Now we will set up two screens in the screens/directory
- Authentication.js: Screen with Facebook with Facebook Sign-in button to initiate the sign-in process.
- Authenticated.js: The screen that users can see only if he is logged in.
The Firebase Project Set up:
We will open the Firebase console to set up the Firebase project. Sign in to the account and click on Create a new Project. This will be the initial step to implement Facebook login using React Native firebase.
![Firebase console for Facebook login using react](https://latitudetechnolabs.com/wp-content/uploads/2022/02/firebase-console-1-768x387.png)
Once you are done with it, the dashboard will be like shown below.
![firebase project for facebook login using react](https://latitudetechnolabs.com/wp-content/uploads/2022/02/firebase-console-project-1-768x378.png)
Furthermore, click on the Android icon. This will integrate an Android app into the Firebase project.
![facebook login using firebase console](https://latitudetechnolabs.com/wp-content/uploads/2022/02/firebase-console-project1-1-768x397.png)
Also, you will need the app’s package name. Visit the AndroidManifest.xml to find out the package name. You will trace this xml file in the android/app/src/main.
![Facebook login using firebase package](https://latitudetechnolabs.com/wp-content/uploads/2022/02/package-name-coding-768x527.png)
Furthermore, download the google-services.json file and locate it in the android/app directory.
Configurations will be present in this file that will permit your app to access the firebase services.
Further, you will need to add configurations to the build.gradle files. Initially, you have to incorporate the google-services plugin inside the android/build.gradle file as a dependency.
buildscript {
dependencies {
// … other dependencies
classpath ‘com.google.gms:google-services:4.3.3’
}
}
Moreover, add the following code to your android/app/build.gradle file. This will execute the plugin.
apply plugin: ‘com.android.application’
apply plugin: ‘com.google.gms.google-services’
The further step will be to configure Firebase for iOS.
Now the next step is to complete the set-up for Firebase. For this, let’s install the @react-native-firebase/app package in the app.
npm install @react-native-firebase/app
Set up Facebook Application:
Setting a Facebook app is a crucial step in making a Facebook login using React Native Firebase. Visit the developers.facebook.com and then click to create a developer account.
Click to the Apps section and create a new app.
You will get the App Dashboard once you create an application. The next step will be to add the Facebook login product to your application from the dashboard.
To find App ID and App secret you need to move to the basic settings. Scroll down until you find the Add Platform once you make a copy of it.
Select Android once you click on it
The further step will be to fill in the Package Name. It will be identical to the package found in AndroidManifest.xml, located in android/app/src/main/.
Fill it as MainActivity for the Class Name
Further, you need to generate it using OpenSSL for the Key Hash. Also, you can refer to Google Code Archive to download it. Extract the same and copy the folder to c: /.
Furthermore, detect the keytool.exe in the JDK directory inside the bin/directory. Remember that usually, JDK is in a location like c:\ProgramFiles\Java\jdk1.8.0_261\bin.
Now run the following code inside the bin/folder.
./keytool -exportcert -alias androiddebugkey -keystore “C:\Documents and Settings\Administrator.android\debug.keystore” | “C:\OpenSSL\bin\openssl” sha1 -binary |”C:\OpenSSL\bin\openssl” base64
Output
4iuaxR+bpCEhMEQslBTwAePpz74=
Set up Firebase Authentication:
Furthermore, we need to do authentication in the Facebook login using React Native Firebase mechanism. Click on the authentication section in the dashboard and then click on the GetStarted button. It will enable the authentication module.
Enable the Facebook authentication in the sign-in method. Furthermore, provide the App secret and App ID from the Facebook Developer Console and then press Save.
Also, add the OAuth redirect URI to the Facebook app configuration. This will complete the set up. Now move to the Facebook Developer console after copying the OAuth redirect URI.
Go to settings in Facebook login under Products. Under Valid OAuth Redirect URI’s in the Client OAuth settings, paste the redirect URI.
Install the auth module after moving to the application.
Install the package @react-native-firebase/auth in our app through the below code
npm install @react-native-firebase/auth
Use the Firebase Android BoM to declare the dependency for the authentication module. This should be done in android/app/build.gradle file.
dependencies {
// Add these lines
implementation platform(‘com.google.firebase:firebase-bom:26.3.0’)
implementation ‘com.google.firebase:firebase-auth’
}
Further we install the React Native Facebook SDK.
npm install react-native-fbsdk
Add mavenCentral() under repositories in buildscript. This should be done in android/build.gradle.
buildscript {
repositories {
google()
jcenter()
// Add this line
mavenCentral()
}
}
Under dependencies, add the following code In android/app/build.gradle
implementation ‘com.facebook.android:facebook-android-sdk:[5,6)’
Further, add the Facebook App ID to the project’s strings file.
<resources>
<string name=”app_name”>RNFirebaseFacebookAuth</string>
<string name=”facebook_app_id”><– Your App ID here –></string>
</resources>
Add the uses-permission element under manifest. This should be done in the AndroidManifest.xml file.
<uses-permission android:name=“android.permission.INTERNET” />
Add the meta-data to the app element:
<application android:label=“@string/app_name” …>
…
<meta-data android:name=“com.facebook.sdk.ApplicationId” android:value=“@string/facebook_app_id”/>
…
</application>
Sign-in
Now let’s create a function called as signIn in App.js. It will be called once the user presses the Sign in button. The next step will be wrapping the entire code inside the function in a try/catch block. This will display the error that arises due to sign inflow.
async function signIn() {
try {
// Code goes here
} catch (error) {
alert(error);
}
}
To log in with permissions we further use the Login Manager. We will pass an array of permissions that are needed in the app to the function.
const result = await LoginManager.logInWithPermissions([
‘public_profile’,
’email’,
]);
If the user canceled the process, then isCancelled property will be present in the result. We will throw an error that the catch block will handle.
if (result.isCancelled) {
throw ‘User cancelled the login process’;
}
We should get the users AccessToken once signed in.
const data = await AccessToken.getCurrentAccessToken();
Let’s throw an error if the data is empty.
if (!data) {
throw ‘Something went wrong obtaining access token’;
}
The next will be an access token used to create a credential. After that, sign in the user into the application.
const facebookCredential = auth.FacebookAuthProvider.credential(data.accessToken);
return auth().signInWithCredential(facebookCredential);
The complete code for the signIn function will be as follow.
async function signIn() {
try {
// Login the User and get his public profile and email id.
const result = await LoginManager.logInWithPermissions([
‘public_profile’,
’email’,
]);
// If the user cancels the login process, the result will have a
// isCancelled boolean set to true. We can use that to break out of this function.
if (result.isCancelled) {
throw ‘User cancelled the login process’;
}
// Get the Access Token
const data = await AccessToken.getCurrentAccessToken();
// If we don’t get the access token, then something has gone wrong.
if (!data) {
throw ‘Something went wrong obtaining access token’;
}
// Use the Access Token to create a facebook credential.
const facebookCredential = auth.FacebookAuthProvider.credential(data.accessToken);
// Use the facebook credential to sign in to the application.
return auth().signInWithCredential(facebookCredential);
} catch (error) {
alert(error);
}
}
Display Authenticated Screen:
The onAuthStateChanged event will be triggered now. But this will happen whenever the authentication state of the user changes inside the application.
You can also set an event handler for this listener. This handler will get the user object. When the user sign-out, the user object will be null.
Using auth().currentUser you can access the current authenticated user’s details from anywhere in the app. The user object will contain the email, displayName and photoURL that were copied from Facebook to Firebase.
The next will be tracking the user’s authentication. Now the next will be setting the default value to false.
const [authenticated, setAutheticated] = useState(false);
If the user object in the onAuthStateChanged handler is not null then we will set the authenticated state to true.
auth().onAuthStateChanged((user) => {
if(user) {
setAutheticated(true);
}
})
We should display the authenticated screen in case if the user is authenticated
if (authenticated) {
return <Authenticated />;
}
return <Authentication signIn={signIn} />;
Here to display the email ID, name and user’s profile picture, I’m using auth().currentUser in the Authenticated screen.
const user = auth().currentUser;
return (
<View style={styles.screen}>
<Text style={styles.title}>You‘re Logged In</Text>
<Image source={{ uri: user?.photoURL }} style={styles.image} />
<Text style={styles.text}>{user?.displayName}</Text>
<Text style={styles.text}>{user?.email}</Text>
<View style={{ marginTop: 30 }}>
<Button title=“Signout” onPress={() => auth().signOut()} />
</View>
</View>
);
Sign Out
Now its turn about sign out step in the process of Facebook login using React Native Firebase. We will use the signOut method in the auth module. It will be useful to sign a user out from the app.
Import the auth module in Authenticated.js
Import auth from ‘@react-native-firebase/auth’
Further, when the user presses the signout button the signout method should be called.
<Button title=“Signout” onPress={() => auth().signOut()} />
The auth module will sign the user out from the app when the user presses the button. It will also trigger the onAuthStateChanged listener. Instead of the user object, the handler will receive the null.
If we receive null, we should set the authenticated state to false.
auth().onAuthStateChanged((user) => {
if(user) {
setAuthenticated(true);
} else {
setAuthenticated(false);
}
})
So following the above steps, we can easily implement Facebook login with Firebase. Keep in mind that you need to follow it step by step. Moreover, connect with us if you are looking forward to hire a React Native developer.