Mastering Social Sign-In in React Native: A Comprehensive Guide

Nowadays in mobile apps most apps are using social login for authentication of users. Integrating social sign-in options like Apple, Google, and Facebook into your React Native app can enhance the user experience by providing easy and quick authentication methods. In this guide, we will walk you through the steps to implement social sign-in using a single SDK. This tutorial includes all the necessary configurations and setup details for both iOS and Android platforms.

Step 1: Installation

First, you need to install the required packages. You can do this using either npm or yarn:

npm install rn-social-login react-native-fbsdk-next 
@invertase/react-native-apple-authentication 
@react-native-google-signin/google-signin

OR

yarn add rn-social-login react-native-fbsdk-next 
@invertase/react-native-apple-authentication 
@react-native-google-signin/google-signin

Next, install the necessary CocoaPods:

cd ios && pod install && cd ..

Step 2: Google Sign-In Configuration

To use Google Sign-In in your app, you’ll need to set up your project in the Google Developer Console and obtain OAuth 2.0 Client IDs for Android, iOS, and Web. Here’s how you can do it:

How to Get Client Id for Android/iOS/Web for Google Sign-In

🔷 Obtaining iOS Client ID

Go to Google API Console:

Create a New Project:

  • Click on the project dropdown at the top of the page and select “New Project”.
  • Enter a project name and click “Create”.

Enable APIs and Services:

  • In the API library, search for “Google Sign-In API” and enable it.

Configure OAuth Consent Screen:

  • In the left sidebar, go to “OAuth consent screen”.
  • Select “External” and click “Create”.
  • Fill in the required information and save.

Create iOS OAuth Client ID:

  • In the left sidebar, go to “Credentials”.
  • Click “Create Credentials” and select “OAuth Client ID”.
  • Select “iOS” as the application type.
  • Enter your Bundle ID and click “Create”.
  • Your iOS Client ID will be displayed. Copy it for later use.

🔷 Registering an Android App with OAuth Client ID

Create Android OAuth Client ID:

  • In the Google API Console, go to “Credentials”.
  • Click “Create Credentials” and select “OAuth Client ID”.
  • Select “Android” as the application type.
  • Enter your Package Name.
  • Generate your SHA-1 Certificate Fingerprint (see instructions below) and enter it.
  • Click “Create”.
  • Your Android Client ID will be displayed. Copy it for later use.

🔷 Generating SHA-1 Certificate Fingerprint

Using Keytool:

  • Open a terminal and run the following command:
keytool -list -v -keystore YOUR_RELEASE_KEY_PATH -alias YOUR_RELEASE_KEY_ALIAS 
-storepass YOUR_KEYSTORE_PASSWORD -keypass YOUR_KEY_PASSWORD
  • Replace YOUR_RELEASE_KEY_PATH, YOUR_RELEASE_KEY_ALIAS, YOUR_KEYSTORE_PASSWORD, and YOUR_KEY_PASSWORD with your actual keystore details.
  • Copy the SHA-1 Certificate Fingerprint from the output.

🔷 Obtaining Web Client ID

Create Web OAuth Client ID:

  • In the Google API Console, go to “Credentials”.
  • Click “Create Credentials” and select “OAuth Client ID”.
  • Select “Web application” as the application type.
  • Enter a name for your client ID.
  • Add your authorized redirect URIs.
  • Click “Create”.
  • Your Web Client ID will be displayed. Copy it for later use.

Now we will configure Google Sign-In in React Native and implement the configuration for both Android and iOS.

Android Configuration

1. Download the Configuration File: Download google-services.json from Firebase and place it in the android/app directory.

2. Update android/build.gradle:

buildscript {
    ext {
        buildToolsVersion = "a.b.c"
        minSdkVersion = x
        compileSdkVersion = y
        targetSdkVersion = z
        googlePlayServicesAuthVersion = "20.7.0"
 }
dependencies {
        classpath 'com.google.gms:google-services:4.4.0'
 }
}

3. Update android/app/build.gradle:

apply plugin: "com.android.application"
apply plugin: "org.jetbrains.kotlin.android"
apply plugin: "com.facebook.react"
apply plugin: 'com.google.gms.google-services'

iOS Configuration

  1. Download the Configuration File: Download GoogleService-Info.plist from Firebase and place it in the ios/<app_name> directory.
  2. Configure URL types in the Info panel (see screenshot) add a URL with scheme set to your REVERSED_CLIENT_ID (found inside GoogleService-Info.plist or Google Cloud console).

Step 3: Facebook Sign-In Configuration

To use the sign-in with Facebook in a mobile app you need to have a facebook developer account. You can follow below steps to create an account in Facebook developer account and after that you can create an app in that and do the configuration.

Create a Facebook Developer Account

  • Go to the Facebook for Developers website.
  • Click on Get Started and log in with your Facebook account.
  • Follow the on-screen instructions to set up your developer account.

Create a New App

  • After logging in, go to the App Dashboard.
  • Click Create App.
  • Choose the type of app you are creating (e.g., For Everything Else).
  • Click Continue and fill in the required details (App Name, App Contact Email, etc.).
  • Click Create App ID and complete any security checks.

Register Your Android App

  • In the App Dashboard, select Settings > Basic.
  • Scroll down to the Add Platform section and select Android.
  • Fill in the required fields:
    Package Name: Your app’s package name.
    Default Activity Class Name: Your app’s main activity class.
  • Save your changes.

Register Your iOS App

  • In the App Dashboard, select Settings > Basic.
  • Scroll down to the Add Platform section and select iOS.
  • Fill in the required fields:
    Bundle ID: Your app’s bundle identifier.
  • Save your changes.

Obtain App ID and Client Token

  • In the App Dashboard, go to Settings > Basic.
  • Copy the App ID from the App ID field.
  • Scroll down to the Client Token section. If you don’t see a Client Token, go to Settings > Advanced and copy the token from the Client Token field.

To access Facebook Sign-In in a mobile app, we need to configure it in React Native as well as in the Android and iOS sides.

Android Configuration

  1. Open the file Gradle Scripts | build.gradle (Project: <your_project>) and add the following:
    mavenCentral()
  2. Open the file Gradle Scripts | build.gradle (Module: app) and add the following to the dependencies section:
    implementation 'com.facebook.android:facebook-android-sdk:latest.release'
  3. Open the /app/res/values/strings.xml file in your app project. Add string elements with the names facebook_app_id and facebook_client_token, and set the values to your App ID and Client Token. For example, if your app ID is 1234 and your client token is 56789 your code looks like the following:
    <string name="facebook_app_id">1234</string>
    
    <string name="facebook_client_token">56789</string>
  4. Open the /app/manifests/AndroidManifest.xml file in your app project. Add meta-data elements to the application element for your app ID and client token:
    <uses-permission android:name="android.permission.INTERNET"/>
    ...
    <application android:label="@string/app_name" ...>
    ...
    <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"/>
    ...
    </application>
  5. Create a Release Key Hash: You need this key hash for android which you need to add in facebook developer console:
    keytool -exportcert -alias <RELEASE_KEY_ALIAS> -keystore 
    <RELEASE_KEY_PATH> | openssl sha1 -binary | openssl base64

iOS Configuration

  1. To integrate Facebook into your app, follow these steps to modify your Info.plist file. So Add the following XML snippet into the body of your file (inside <dict>…</dict>):
    <key>CFBundleURLTypes</key>
    <array>
       <dict>
         <key>CFBundleURLSchemes</key>  
         <array>
            <string>fbAPP-ID</string>
         </array>
       </dict>
    </array>
    <key>FacebookAppID</key>
    <string>APP-ID</string>
    <key>FacebookClientToken</key>
    <string>CLIENT-TOKEN</string>
    <key>FacebookDisplayName</key>
    <string>APP-NAME</string>
  2. Replace the placeholders in the XML snippet with your actual Facebook app values:
    CFBundleURLSchemes: Replace fbAPP-ID with your actual Facebook App ID. This URL scheme allows your app to open via specific URLs.
    FacebookAppID: Replace APP-ID with your actual Facebook App ID. This key identifies your app with Facebook.
    FacebookClientToken: Replace CLIENT-TOKEN with the client token from your Facebook App Dashboard (found under Settings > Advanced > Client Token). This token is used for secure communication with Facebook services.
    FacebookDisplayName: Replace APP-NAME with the name of your app. This name appears in Facebook dialogs and notifications.
  3. Add the following snippet to use Facebook dialogs (e.g., Login, Share, App Invites) that can perform an app switch to Facebook apps:
    <key>LSApplicationQueriesSchemes</key>
    <array>
    <string>fbapi</string>
    <string>fb-messenger-share-api</string>
    </array>
  4. Here’s an example of how the Info.plist will look with the Facebook integration snippets added and placeholders replaced with actual values:
    <dict>
       ...
       <key>CFBundleURLTypes</key>
       <array>
         <dict>
            <key>CFBundleURLSchemes</key>
            <array>
              <string>fb123456789</string> <!-- Replace with your AppID -->
            </array>
         </dict>
       </array>
    <key>FacebookAppID</key>
    <string>123456789</string> <!-- Replace with your AppID -->
    <key>FacebookClientToken</key>
    <string>abcd1234efgh5678ijkl</string> <!-- Replace with your Client Token -->
    <key>FacebookDisplayName</key>
    <string>MyAppName</string> <!-- Replace with your App Name -->
    <key>LSApplicationQueriesSchemes</key>
    <array>
      <string>fbapi</string>
      <string>fb-messenger-share-api</string>
    </array>
    ...
    </dict>

Elevate your React Native App's Security and User Experience with Social Athentication. Hire Our Developers Now!

Step 4: Apple Sign-In Configuration

Implementing Apple Sign-In in React Native involves several steps, including setting up your Apple developer account, configuring your app in the Apple Developer portal, and integrating the Apple Sign-In functionality in your React Native app.

Set Up Your Apple Developer Account

Enroll in the Apple Developer Program:

  • Make sure you’re enrolled in the Apple Developer Program. This is required to use Sign in with Apple.

Create an App ID:

  • Go to the Apple Developer portal.
  • Navigate to “Certificates, Identifiers & Profiles.”
  • Under Identifiers, click the “+” button to create a new App ID.
  • Enable the “Sign in with Apple” capability.

Create a Key for Sign-In with Apple:

  • In the developer portal, create a new key.
  • Enable Sign in with Apple for this key.
  • Download the key and note the key ID.

Integrating Social Sign-Ins in React Native: Updating AppDelegate.m

To enable social sign-ins (Google, Facebook, and Apple) in your React Native project, you’ll need to update your AppDelegate.m file. Follow these steps to set up your app for these integrations properly.

Add the Necessary Imports

First, import the required headers at the top of your AppDelegate.m file. These imports include the SDKs for Google Sign-In, Facebook, and the necessary modules.

#import <RNGoogleSignin/RNGoogleSignin.h>
#import <React/RCTLinkingManager.h>
#import <AuthenticationServices/AuthenticationServices.h>
#import <SafariServices/SafariServices.h>
#import <FBSDKCoreKit/FBSDKCoreKit-Swift.h>
#import <GoogleSignIn/GoogleSignIn.h>

Initialize the Facebook SDK

Inside the didFinishLaunchingWithOptions method, add the following code to initialize the Facebook SDK. This is crucial for the Facebook login to work properly.

// Initialize Facebook SDK
[[FBSDKApplicationDelegate sharedInstance] application:application
didFinishLaunchingWithOptions:launchOptions];

Handle URL Schemes for Each Sign-In Method

Add the following method to handle URL schemes. This method will ensure that the appropriate SDK processes the URL when the app is opened via a URL scheme, which is common in OAuth flows.

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> 
*)options
{
  // Handle URL for Google Sign-In
  if ([GIDSignIn.sharedInstance handleURL:url]) {
     return YES;
}

  // Handle URL for React Native Linking
  if ([RCTLinkingManager application:app openURL:url
 options:options]) {
     return YES;
}

// Handle URL for Facebook Sign-In
if ([[FBSDKApplicationDelegate sharedInstance] application:app openURL:url options:options]) {
return YES;
 }

return NO;
}

Usage Example

Here’s an example of how to use the rn-social-login component in your app:

import type { User } from '@react-native-google-signin/google-signin';
import * as React from 'react';

import { Alert, StyleSheet, Text, View } from 'react-native';
import {
     SocialLogin,
     type FacebookSignInProps,
     type SocialLoginHandle,
     type AppleSignInProps,
}   from 'rn-social-login';

export default function App() {
    // Create a ref for the SocialLogin component
    const socialLoginRef = React.useRef<SocialLoginHandle>(null);

    // Initialize social logins on component mount
    React.useEffect(() => {
      socialLoginRef?.current?.initSocialLogins({
        iosClientId: '<YOUR_IOS_CLIENT_ID>',
        webClientId: 'YOUR_WEB_CLIENT_ID',
      });
}, []);

/**
* Callback function for successful Google sign-in.
* @param userInfo - Information about the signed-in user.
*/
const onGoogleSuccess = (userInfo: User) => {
  console.log('Google login success', userInfo);
  Alert.alert('Social Login', 'Google login success.');
};

/**
* Callback function for Google sign-in error.
* @param error - Error object.
*/
const onGoogleError = (error: any) => {
  console.log('Google login error', error);
};

/**
* Callback function for successful Facebook sign-in.
* @param token - Access token from Facebook.
* @param currentProfile - Current user profile from Facebook.
*/
const onFacebookSuccess = ({
  token,
  currentProfile,
}: FacebookSignInProps) => {
  console.log('Facebook login token', token);
  console.log('Facebook login profile', currentProfile);
  Alert.alert('Social Login', 'Facebook login success.');
};

/**
* Callback function for Facebook sign-in error.
* @param error - Error object.
*/
const onFacebookError = (error: any) => {
  console.log('Facebook login error', error);
};

/**
* Callback function for successful Apple sign-in.
* @param appleAuthRequestResponse - Response from Apple authentication request.
* @param credentialState - State of the Apple credential.
*/
const onAppleSuccess = ({
  appleAuthRequestResponse,
  credentialState,
}: AppleSignInProps) => {
  console.log(
    'Apple login appleAuthRequestResponse',
    appleAuthRequestResponse
  );
  console.log('Apple login credentialState', credentialState);
  Alert.alert('Social Login', 'Apple login success.');
};

/**
* Callback function for Apple sign-in error.
* @param error - Error object.
*/
const onAppleError = (error: any) => {
  console.log('Apple login error', error);
};

return (
  <View style={styles.container}>
    <Text style={styles.title}>{'Login With'}</Text>
    <SocialLogin
      ref={socialLoginRef}
      onGoogleSignInSuccess={onGoogleSuccess}
      onGoogleSignInError={onGoogleError}
      signOutGoogleSignBeforeLogin
      onFacebookSignInSuccess={onFacebookSuccess}
      onFacebookSignInError={onFacebookError}
      onAppleSignInSuccess={onAppleSuccess}
      onAppleSignInError={onAppleError}
     />
   </View>
  );
}

/** Styles for the App component */
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white',
},
box: {
  width: 60,
  height: 60,
  marginVertical: 20,
},
title: {
  fontSize: 16,
  color: 'black',
  marginBottom: 10,
  fontWeight: '700',
 },
});
coma

Conclusion

This blog has detailed integrating social login (Apple, Google, Facebook) using a single SDK. This SDK streamlines the integration of Google, Facebook, and Apple sign-ins into your app, reducing complexity and saving time. By following the step-by-step guide, you’ll configure each social login, create necessary developer accounts, and implement the required code seamlessly. This approach not only simplifies the login process but also improves user experience by providing familiar authentication options.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?