Get Started with React Native + Google Sign In

Get Started with React Native + Google Sign In

·

6 min read

In React Native how can i add google signin using react-native-google-signin?. I will be guiding you in this step by step article on how to implement Login with Google in your React Native app.

I will be using a React Native Community supported package called react-native-community/google-signin.

Note : This post is made for react-native >= 0.60, if you are using react-native <= 0.59.x then this is not for you

google-signin

##Features

  • Support all 3 types of authentication methods (standard, with server-side validation or with offline access (aka server-side access))
  • Promise-based API consistent between Android and iOS
  • Typings for TypeScript and Flow
  • Native signin buttons

Versions

React Native 0.61.5

react-native-community/google-signin 4.0.0

#Steps

  • First, create the App using this command in terminal
npx react-native init TypeYourAppNameHere
  • Navigate to RNGoogleSignInDemo in the terminal like this
cd TypeYourAppNameHere
  • Now install react-native-community/google-signin dependency in your app
yarn add @react-native-community/google-signin

OR

npm install --save @react-native-community/google-signin

Since React Native >= 0.60 AutoLinking is supported therefore we don't need to run linking command.

But we do need to do some configuration in the native side but I promise it will be easy.

There are two ways to do this, with or without Firebase and I will be using the one with the Firebase. But for the other one, I can make a separate post for it. Do let me know should I?

Firebase

  • Search for Firebase and go to Firebase Console
  • Create a project [ I have already created ] by clicking on Add Project.

firebase console

  • Type your project Name after that click Continue

firebase console

  • Choose whether you want to add Analytics or not it's up to your preferences. By default, it's enabled. Press Continue.

firebase console

Now your project is created.

firebase console

  • Click the android icon in the firebase Console Dashboard

firebase console

  • Fill in the following fields of "Add Firebase to your Android app" to generate config file ( i.e. google-services.json)

    • Android package name
    • Debug signing certificate SHA-1 firebase console
  • For App's Package name you can find in android/app/main/AndroidManifest.xml file

AndroidManifest.xml

  • For Debug signing certificate SHA-1

In terminal type command for Debug SHA1 (root of the project)

Mac/Linux

keytool -J-Duser.language=en -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

Windows

– Change the directory to the JDK bin directory. The path of the JDK depends upon the operating system you are using

cd C:\Program Files\Java\jdk1.8.0_121\bin

– Now we have to run the following command using the keytool.exe file in JDK/bin

keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

terminal

If you don't like terminal then you use can Android Studio instead

Android Studio 1 Android Studio 2

  • When you are done registering your android app with firebase then Download the Config file and place it in android/app

firebase2.2.png firebase2.2.1.png

  • Add Firebase SDK in Project-level build.gradle i.e. android/build.gradle firebase2.3.png

    buildscript {
      ext {
          buildToolsVersion = "28.0.3"
          minSdkVersion = 16
          compileSdkVersion = 28
          targetSdkVersion = 28
          googlePlayServicesAuthVersion = "18.0.0" // Add this line
      }
      repositories {
          google()
          jcenter()
      }
      dependencies {
          classpath("com.android.tools.build:gradle:3.4.2")
          classpath 'com.google.gms:google-services:4.3.3' // Add this line
          // NOTE: Do not place your application dependencies here; they belong
          // in the individual module build.gradle files
      }
    }
    
  • Add Google Play Services plugin in App-level build.gradle (android/appp/build.gradle):

apply plugin: 'com.google.gms.google-services' // Add at end of the file

e.g.

firebase2.4.png

  • In firebase, you will need to enable Google option in SignIn Method section

firebase2.5.png

  • While enabling Google, do copy the Web Client ID from there, we need this later on. firebase2.6.png

Let's get our hands dirty with the code

I will be making a simple app of just two components to App.js (already exists by default) and second will be Home.js.

  • Import Public Api of @react-native-community/google-signin
import {
  GoogleSignin,
  GoogleSigninButton,
  statusCodes,
} from '@react-native-community/google-signin';
  • But before you can use above imports you need call once, configure of GoogleSignin. You can call it in ComponentDidMount life Cycle method or you can use useEffect Hook
GoogleSignin.configure({
 webClientId: WebClientID, // client ID of type WEB for your server(needed to verify user ID and offline access)
 offlineAccess: true, // if you want to access Google API on behalf of the user FROM YOUR SERVER
 forceCodeForRefreshToken: true, // [Android] related to `serverAuthCode`, read the docs link below *.
 accountName: '', // [Android] specifies an account name on the device that should be used
    });
  • Sign in function

 signIn = async () => {
    try {
      await GoogleSignin.hasPlayServices();
      const info = await GoogleSignin.signIn();
      console.warn({userInfo: info});
      setUserInfo(info);
    } catch (error) {
      if (error.code === statusCodes.SIGN_IN_CANCELLED) {
        // user cancelled the login flow
      } else if (error.code === statusCodes.IN_PROGRESS) {
        // operation (e.g. sign in) is in progress already
      } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
        // play services not available or outdated
      } else {
        // some other error happened
      }
    }
  };
  • Sign out function
  signOut = async () => {
    try {
      await GoogleSignin.revokeAccess();
      await GoogleSignin.signOut();
      setUserInfo(null); // Remember to remove the user from your app's state as well
    } catch (error) {
      console.error(error);
    }
  };

Demo App Preview

ezgif.com-optimize00986b78df17d105.gif

Do check the official Docs.

Summary

  • Install react-native-google-signin package using Npm or Yarn (which ever you prefer).
  • Create a firebase project if it wasn't create already.
  • Configure your firebase project and add your system's SHA-1 key(s) and your React native App's Package Name.
  • Download google-services.json [ Android ] / google-services.plist [ iOS ] and place it in your React Native Project.
  • Import functions provided by react-native-google-signin in your code according to your requirements.

So what else do you use to authenticate your users in your App?

Do not forget to share it with someone who would find helpful.

See Ya