Google Login in React Native (Android) apps with Firebase

April 26, 2020

Google Login in React Native (Android) apps with Firebase

Google login — What and why

There are several reasons why you should use a Google login in your app

  • Ease of use — When a new user uses your app, only two buttons clicks are required to login using Google. In other scenario, user will have to type in an email/password and login
  • No “forgot password”— When your app uses Google login, the user does not have to worry about forgetting password for your app’s login
  • No “verify email” — If you use a custom-email authentication of your own, you will have to verify the email if it is a valid one or not. Google login will always have a valid email/phone number associated.
  • Single solution —Google login can allow your users to use single login credentials across multiple devices
  • Google integration — If your app uses Google authentication, you can use Google APIs inside your app as well. This can include fetching user tweets etc.
  • Trust — Nowadays, people generally trust social logins more over custom email logins. Social logins follows standard privacy protocols and hence are more reliable for information sharing

    Steps for Google authentication

    We will follow these step-by-step instructions to create our React Native app with Google authentication

    Step 1: Create Firebase Project and Add android platform

    ‌Step 2: Enable Google Sign-In in Firebase project

    Step 3: Create a Basic React Native app

    ‌Step 4: Install thereact-native-google-signinpackage for Google Login

    Step 5: Implement Google auth functions in RN app

    Step 6: Test your app on Android

    Step 7: Use Firebase to store user info and handle Auth

Step Main: Create a SHA-1 Signature

This is an important step where many developers commit mistake. That’s why Step 0

This is a way for the app and Firebase to recognize the system from which the app was developed. It is generated based on the system and yourkeystorefile.

Generate the key using following command

keytool -exportcert -keystore <<keystore path debug or relase>> -list -v

If you are using Debug keystore of react native then enter password : android

Use thiskeystorefile location to generate SHA-1 signature. Keep the signature safe for further steps. SHA-1 looks like this

AE:Y2:16:06:CX:X3:RR:2C:XX:0D:AE:Y2:16:06:CX:X3:AE:Y2:16:06:CX:X3

Step 1: Create Firebase Project

Step 1:For authentication, we need a back-end. For this tutorial, Firebase is our back-end, so we need to configure few things in Firebase. First of all we’ll create a new Firebase project and new app inside it.

Step 2:Now that the project is created, create a new Android app in the project dashboard.

Step 3:Add theSHA1key you generated in Step Main and add it inDebug signing certificate SHA-1field

step 4:Just mention the correct package name of your app in theAndroid package nameinput. For me, it is com.awsomeapp. Give it a nickname to remember.

Next step, download thegoogle-services.jsonfile and put it in theandroid/appfolder of your project. You can skip rest of the steps for now. Your app is created now, and you should see it in the dashboard.

step 5 :Now that your app is connect to Firebase project, we need to go into our Firebase console and enable Google authentication for our app.

‌Once you’re inside the app’s dashboard, you’re going to go into

Authentication → Sign-In Method → Google

and click theEnabletoggle.

Install package

Install the package using

 $ yarn add react-native-google-signin

Note: For React Native ≥0.60, you don’t need to manually link most packages with React Native. It is done automatically on app build

$ react-native link react-native-google-signin

Add google-services.json file to project

If you haven’t done it yet, download thegoogle-services.jsonfile from your Firebase project and put it in theandroid/appfolder of your RN project.

Source Code For How to Login with Google

import  React,{useEffect} from 'react';
import { View ,Text, Button} from 'react-native';
import {
    GoogleSignin,
    GoogleSigninButton,
    statusCodes,
  } from 'react-native-google-signin';
  import { useDispatch } from 'react-redux'
  import { StackActions } from '@react-navigation/native';
  
const Login=({navigation})=> {
  const dispatchRedux = useDispatch();
  console.info(navigation)
 
  const _signIn = async () => {
    try {
      await GoogleSignin.hasPlayServices({
        showPlayServicesUpdateDialog: true,
      });
      const {user} =  await GoogleSignin.signIn();
      console.log(user)
      dispatchRedux({type:"UserInfo",payload:user})
      navigation.dispatch(
      StackActions.replace('Home')
      )
    } catch (error) {
      console.log('Message', error.message);
      if (error.code === statusCodes.SIGN_IN_CANCELLED) {
        console.log('User Cancelled the Login Flow');
      } else if (error.code === statusCodes.IN_PROGRESS) {
        console.log('Signing In');
      } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
        console.log('Play Services Not Available or Outdated');
      } else {
        console.log('Some Other Error Happened');
      }
    }
  }
  useEffect(() => {
    GoogleSignin.configure({
        scopes: ['https://www.googleapis.com/auth/userinfo.email'],
        webClientId: 'xxxxxxxxxxx.apps.googleusercontent.com',
        iosClientId:'xxxxxxxxxxxxprt4atbpsmi.apps.googleusercontent.com'
      });

  }, [])
    return (
      <View style={{ flex: 1,backgroundColor:'white',alignItems:'center',justifyContent:'center'}}>
        <GoogleSigninButton
              style={{ width: 312, height: 48 }}
              size={GoogleSigninButton.Size.Wide}
              color={GoogleSigninButton.Color.Dark}
              onPress={_signIn}
            />
            <Text style={{margin:20,textAlign:'center',paddingTop:5,fontSize:16}}>Google Login only contain your Email,Name and Profile Image</Text>
      </View>
    );
  }
  export default Login  

Source Code For check user is login or not with Logout

 const isSignedIn = async () => {
    const isSignedIn = await GoogleSignin.isSignedIn();
    if(isSignedIn){
      const {user} = await GoogleSignin.getCurrentUser();
      dispatchRedux({type:"UserInfo",payload:user})
      navigation.dispatch(
      StackActions.replace('Home')
     )
    }
  }
  const signOut = async () => {
    try {
        await GoogleSignin.revokeAccess();
        let Logout= await GoogleSignin.signOut();
        console.info(Logout)
        if(Logout===null){
          navigation.dispatch(
             StackActions.replace('Login')
           )
        }
    } catch (error) {
      console.error(error);
    }
  };

Written by Manoj Bhardwaj who lives and works in Dharamshala Himachal Pradesh (India). My stackoverflow