React Native Tutorial: Build an Educational App with Expo

Add Google Authentication to Your Expo React Native App (2024)

This article explains how to integrate Google authentication into your Expo React Native application. Google authentication allows users to sign in to your app using their existing Google accounts, providing a seamless and secure login experience. An accompanying video walks through the full process.

Setting up Google authentication with Expo can seem tricky. This guide simplifies the process, taking you through installing the necessary library, configuring your Google Cloud project, and obtaining the required credentials (Android client ID, iOS client ID, and web client ID). You’ll learn how to create a project in Google Cloud, configure the OAuth consent screen, and generate the necessary SHA-1 certificate fingerprint. Finally, you’ll implement the Google sign-in functionality in your Expo app.

Installing the Required Library

The first step is to install the Expo Google Authentication library. This library simplifies the process of interacting with Google’s authentication services within your Expo application.

Open your terminal, navigate to your project directory, and run the following command:

expo install expo-auth-session expo-random

This command installs both the expo-auth-session and expo-random libraries, which are necessary for handling the authentication flow and generating secure random values, respectively.

Setting Up Your Google Cloud Project

Next, you need to configure a project in the Google Cloud Console to enable Google Sign-In for your application.

  • Go to the Google Cloud Console and sign in with your Google account.
  • If you don’t have a project yet, create a new one by clicking on the project dropdown at the top and selecting “New Project.” Give your project a name and click “Create.”
  • Once your project is created, make sure it’s selected in the project dropdown.

Configuring the OAuth Consent Screen

The OAuth consent screen is what users will see when they sign in with Google. It tells them what information your app is requesting.

  • In the Google Cloud Console, navigate to “APIs & Services” -> “OAuth consent screen.”
  • Select the user type as “External” and click “Create.”
  • Fill in the required information, such as the application name, support email, and developer email. You can also add a logo and links to your privacy policy and terms of service.
  • Click “Save and Continue” through the remaining steps.
  • Back on the dashboard, click “Publish App” to make your app available for Google Sign-In.

Creating Credentials

Now you need to create the credentials that your app will use to authenticate with Google.

  • In the Google Cloud Console, navigate to “APIs & Services” -> “Credentials.”
  • Click “Create Credentials” and select “OAuth client ID.”
  • Select “Android” as the application type.
  • Give your client ID a name.
  • Enter your app’s package name. You can find this in your app.json file under the android.package key. For example: com.yourcompany.yourapp

To get the SHA-1 certificate fingerprint, follow these steps:

  • Make sure you have EAS CLI installed: npm install -g eas-cli
  • Create a file named eas.json in your project’s root directory with the following content:

{ "build": { "development": { "distribution": "internal", "android": { "gradleCommand": ":app:assembleDebug" }, "ios": { "buildConfiguration": "Debug" } }, "preview": { "distribution": "internal" }, "production": {} }, "submit": { "production": {} } }

  • Run the following command in your terminal: eas credentials
  • Select “development” when prompted.
  • The command will guide you through creating or using an existing keystore and provide the SHA-1 fingerprint.
  • Copy the SHA-1 fingerprint and paste it into the Google Cloud Console.
  • Click “Create.”

You’ll now have an Android client ID. You might also need an iOS client ID and a web client ID depending on the platforms you are targeting. Follow the same process, selecting "iOS" or "Web application" as the application type when creating the credentials.

Implementing Google Sign-In in Your Expo App

Now that you have the necessary credentials, you can implement the Google Sign-In functionality in your Expo app.

First, import the necessary modules from the expo-auth-session and expo-random libraries:

javascript import as AuthSession from ‘expo-auth-session’; import as Random from ‘expo-random’; import { Platform } from ‘react-native’;

Then, define your Google authentication request:

javascript const discovery = { authorizationEndpoint: ‘https://accounts.google.com/o/oauth2/v2/auth‘, tokenEndpoint: ‘https://www.googleapis.com/oauth2/v4/token‘, };

const useProxy = Platform.select({ web: true, default: false }); const redirectUri = AuthSession.makeRedirectUri({ useProxy });

Replace YOUR_ANDROID_CLIENT_ID, YOUR_IOS_CLIENT_ID, and YOUR_WEB_CLIENT_ID with the actual client IDs you obtained from the Google Cloud Console.

Create a function to handle the Google Sign-In process:

javascript const [request, response, promptAsync] = AuthSession.useAuthRequest( { clientId: YOUR_WEB_CLIENT_ID, // Use web client ID for both Android and iOS scopes: [‘profile’, ’email’], redirectUri, }, discovery );

React.useEffect(() => { if (response?.type === ‘success’) { const { authentication } = response; getUserInfo(authentication.accessToken); } }, [response]);

const getUserInfo = async (token) => { if (!token) { return; }

try {
  const userInfoResponse = await fetch('https://www.googleapis.com/userinfo/v2/me', {
    headers: { Authorization: `Bearer ${token}` },
  });

  const userInfo = await userInfoResponse.json();
  console.log(userInfo)
} catch (error) {
  console.log(error)
}

}

const signInWithGoogle = () => { promptAsync(); };

This code uses the useAuthRequest hook from expo-auth-session to handle the authentication flow. The promptAsync function initiates the Google Sign-In process when called.

Finally, add a button to your UI that calls the signInWithGoogle function when pressed:

javascript

Share your love

Leave a Reply

Your email address will not be published. Required fields are marked *