Sådan oprettes Google Login i React Native & Firebase

Google-login er en fantastisk loginfunktion, der kan tilbyde dine apps brugere. Det gør det lettere for dem at oprette en konto og logge ind.

Og hvad der er endnu bedre, Firebase gør det ekstremt nemt for udviklere at tilføje support til Google-login. Men opsætning af React Native-miljøet kan skabe nogle udfordringer, som er fuldt dækket i denne vejledning.

React Native og Firebase SDK gør implementeringen af ​​Google-login ret ligetil. Lad os bygge en simpel app, der kun har en enkelt Google-loginknap. Når brugeren først logger ind på Google, viser vi brugerinformationen hentet fra deres Google-konto samt en logout-knap.

Du kan også tilføje Facebook-login til din app, hvis du er interesseret i at give endnu flere loginindstillinger til dine brugere. Du kan tjekke denne guide til Facebook-login i React Native with Firebase, hvis du ønsker at lære mere om, hvordan du opretter Facebook-login.

Hvorfor bruge en Google-loginknap i mobilapps?

  1. Brug af Google eller andre tredjeparter kan gøre din godkendelsesproces problemfri og venlig. Brugere behøver ikke at spilde tid i registreringsprocessen, hvilket vil forbedre din registrerings- og opbevaringsrate enormt.
  2. Det er sikkert.
  3. Brugere stoler på Google eller Facebook mere end et ukendt sted eller en app på Internettet.
  4. Det giver en god brugeroplevelse. Som bruger har vi lidt tålmodighed over for handlinger eller arbejde, vi skal udføre, især i en temmelig ukendt app, som vi prøver for første gang.

Uden yderligere ado, lad os springe direkte ind i appudviklingsdelen af ​​denne vejledning.

Opsætning af Firebase-projektet

Gå til Firebase-konsollen, og opret et Firebase-projekt:

oprette nyt firebase-projekt

Her skal vi konfigurere Firebase-projektnavnet og app-id'et, så lad os først oprette React Native-appen.

Oprettelse af React Native Project

Først skal vi oprette et React Native-projekt ved hjælp af følgende kommando:

react-native init instamobile-google-login-demo

Her har vi givet projektets navn som instamobile-google-login-demo . Nu skal vi installere pakken react-native-google-signin ved hjælp af følgende kommando:

yarn add react-native-google-singin

Den react-native-google-signinpakke bliver brugt til at implementere Google myndig funktioner i React Native app. Nu skal vi importere de nødvendige moduler og komponenter fra den respektive pakke som vist i nedenstående kodestykke:

import { GoogleSignin, GoogleSigninButton, statusCodes, } from 'react-native-google-signin';

Dernæst er vi nødt til at oprette staterne for at håndtere godkendelsestilstanden og brugerinfoen. Til det bruger vi useStatemodulet som vist i nedenstående kodestykke:

const [loggedIn, setloggedIn] = useState(false); const [userInfo, setuserInfo] = useState([]);

Nu skal vi oprette en logon-funktion til at håndtere godkendelse som vist i nedenstående kodestykke:

_signIn = async () => { try { await GoogleSignin.hasPlayServices(); const {accessToken, idToken} = await GoogleSignin.signIn(); setloggedIn(true); } catch (error) { if (error.code === statusCodes.SIGN_IN_CANCELLED) { // user cancelled the login flow alert('Cancel'); } else if (error.code === statusCodes.IN_PROGRESS) { alert('Signin in progress'); // operation (f.e. sign in) is in progress already } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) { alert('PLAY_SERVICES_NOT_AVAILABLE'); // play services not available or outdated } else { // some other error happened } } };

Dernæst skal vi initialisere opsætningen af ​​Google-loginobjektet ved at udnytte useEffectfunktionen:

useEffect(() => { GoogleSignin.configure({ scopes: ['email'], // what API you want to access on behalf of the user, default is email and profile webClientId: '418977770929-g9ou7r9eva1u78a3anassxxxxxxx.apps.googleusercontent.com', // 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 }); }, []);

Endelig har vi brug for en funktion, der håndterer logout-handlingen. Til det vil vi implementere signOutmetoden som vist i nedenstående kodestykke:

signOut = async () => { try { await GoogleSignin.revokeAccess(); await GoogleSignin.signOut(); setloggedIn(false); setuserInfo([]); } catch (error) { console.error(error); } };

Nu skal vi også gengive komponenterne på skærmen. Til det vil vi gøre brug af forskellige komponenter som Viewog Button:

return (           {!loggedIn && You are currently logged out} {loggedIn && (  )}      );

Nu, hvis vi kører vores projekt i emulatoren, får vi følgende resultater:

google login første skærmbillede

Temmelig sød, ikke? Vi har gennemført implementeringen (både brugergrænsefladen og forretningslogikken) på niveauet React Native i vores projekt.

Som du kan se, har vi en "Log ind med Google" -knap, der konverteres til en logout-knap, når loginhandlingen er gennemført.

Vi skal nu oprette Google SignIn-pakken og Firebase-appen.

Konfiguration af iOS og Android Native projekter

Der er et par opsatte trin, vi skal tage, før projektet fungerer fuldt ud. De er for det meste relateret til den faktiske oprindelige side af appen.

Til iOS

Her kører du bare i VSCode (eller en hvilken som helst terminal) cd ios && pod install. Åbn derefter .xcworkspace- filen i Xcode (fra ios-mappen) og sørg for, at Pods er inkluderet:

installer google login lib i xcode

Til Android

1. Først skal vi linke det oprindelige modul.

  • I RN> = 0,60 skal du ikke have brug for at gøre noget takket være automatisk sammenkædning.
  • I RN <0,60 kørsel .react-native link react-native-google-signin

2. Opdater android / build.gradle med følgende konfiguration:

buildscript { ext { buildToolsVersion = "27.0.3" minSdkVersion = 16 compileSdkVersion = 27 targetSdkVersion = 26 supportLibVersion = "27.1.1" googlePlayServicesAuthVersion = "16.0.1" // <--- use this version or newer } ... dependencies { classpath 'com.android.tools.build:gradle:3.1.2' // <--- use this version or newer classpath 'com.google.gms:google-services:4.1.0' // <--- use this version or newer } ... allprojects { repositories { mavenLocal() google() // <--- make sure this is included jcenter() maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url "$rootDir/../node_modules/react-native/android" } } }

3. Opdater android/app/build.gradlemed følgende konfiguration:

... dependencies { implementation fileTree(dir: "libs", include: ["*.jar"]) implementation "com.android.support:appcompat-v7:23.0.1" implementation "com.facebook.react:react-native:+" implementation(project(":react-native-community_google-signin")) // <--- add this dependency }

Kontroller, at react-native linkdet oprindelige modul er knyttet - men kun hvis du brugte det react-native link!

I skal android/settings.gradle  vi have følgende konfigurationer:

... include ':react-native-google-signin', ':app' project(':react-native-google-signin').projectDir = new File(rootProject.projectDir, '../node_modules/@react-native-community/google-signin/android')

Derefter skal MainApplication.javavi have Google-pakken tilføjet som i følgende kodestykke:

import co.apptailor.googlesignin.RNGoogleSigninPackage; // <--- import public class MainApplication extends Application implements ReactApplication { ...... @Override protected List getPackages() { return Arrays.asList( new MainReactPackage(), new RNGoogleSigninPackage() // <-- this needs to be in the list ); } ...... }

Opsætning af Firebase

Til iOS

Now, we need to get started on the Firebase configuration. In Firebase, we need to set up a Google cloud app. But when we set up the authentication method on Firebase this also creates an Google cloud app.

First, we need to create Firebase iOS app in order to obtain GoogleServiceinfo.plist as shown in the screenshot below:

tilføj nyt firebase-appnavn

Next, we copy the GoogleService-info.plist file to the Xcode project as shown in the screenshot below:

tilføj google serviceplist til xcode

Now, we need to add the reversed client ID present in the GoogleService-info.plist file to the URL Types, as shown in the screenshot below:

få omvendt klient-id fra xcode

Next step is to go to InfoURL Types then fill the URL Schemes as shown in the screenshot below:

tilføj webadresseskema til xcode

For Android

First, we need to create an Android app on Firebase. For that, we need a package name and certificate SHA-1 from our app. Then, we can register the Firebase app as shown below:

Opret ny Android Firebase-app

We can get the package name in MainApplication.java of our project as highlighted in the code snippet below:

find ud af bundnavnet i Android-appen

Next, we can get the SHA-1 key in the Keystore file. In the android/app directory, we can run the command:

cd android/app ; keytool -exportcert -keystore debug.keystore -list -v

Then, the SHA-1 key will appear, as shown in the screenshot below:

generer sha1 til at registrere Android-appen i Firebase

After successfully creating the Firebase setup app, we need to download the google-services.json file and copy it to the directory, as shown in the screenshot below:

tilføj google service json til android app-mappen

Now, the final step is to set up a Google sign-in component in Android.

Installing the React Native Firebase Package

In order to install react-native-firebase package version 6, we need to run the following command in our project command prompt:

# Using npm npm install --save @react-native-firebase/app # Using Yarn yarn add @react-native-firebase/app

The @react-native-firebase/app module must be installed before using any other Firebase service.

For iOS

We already have GoogleService-Info.plist added to Xcode. What is left is to allow Firebase on iOS to use the credentials. The Firebase iOS SDK must be configured during the bootstrap phase of your application.

To do this, we need to open our /ios/{projectName}/AppDelegate.m file, and add the following:

At the top of the file, we need to import the Firebase SDK:

#import 

Within your existing didFinishLaunchingWithOptions method, we need to add the following to the top of the method:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Add me --- \/ if ([FIRApp defaultApp] == nil) { [FIRApp configure]; } // Add me --- /\ // ... }

Finally, we need to run the following command to finalize the installation of the CocoaPods package:

cd ios ; pod install

That's it. Now we have completed the installation of the main Firebase package on iOS

For Android

We need to configure Firebase with Android credentials. To allow Firebase on Android to use the credentials, the google-services plugin must be enabled on the project. This requires modification to two files in the Android directory.

First, add the google-services plugin as a dependency inside your android/build.gradle file:

buildscript { dependencies { // ... other dependencies classpath 'com.google.gms:google-services:4.2.0' // Add me --- /\ } } Lastly, execute the plugin by adding the following to the very bottom of your /android/app/build.gradle file: apply plugin: 'com.google.gms.google-services'

React Native Firebase Authentication Module

After the installation completes, we need to set up the parent Firebase package. Next, we need to install the child module for authentication. For that, we need to open a terminal and run the following command:

yarn add @react-native-firebase/auth

For iOS

We just need to install the pods again in the command prompt:

cd ios/ && pod install

For Android

You can follow the instructions on the official document which is only required if you are using React Native <= 0.59 or need to manually integrate the library.

Activating Google Sign-in on Firebase

We need to go to the Firebase console. Then, in the Authentication section, we need to click on Google as shown in the screenshot below:

godkendelsesmetode i firebase

Next, we need to enable the setup with the following configuration and save the configuration as shown in the screenshot below:

aktivere e-mail med projektsupport

In App.js, we need to import auth from the Firebase package as shown in the code snippet below:

import auth from '@react-native-firebase/auth';

Next, we need to integrate authentication config to the sign-in function. After a successful login, we store the accessToken and idToken to Firebase. Now, we can try to login with Google on our demo React Native app.

_signIn = async () => { try { await GoogleSignin.hasPlayServices(); const {accessToken, idToken} = await GoogleSignin.signIn(); setloggedIn(true); const credential = auth.GoogleAuthProvider.credential( idToken, accessToken, ); await auth().signInWithCredential(credential); } catch (error) {

Now we have successfully completed the integration of Google Sign-in in our React Native app:

resultat af google login med reagerer native

We can see new data that is added to the Firebase Console:

firebase authentication console

Tracking User Status

In order to check the user’s login status, we use Firebase Auth. For that, we need to add the onAuthStateChanged method to useEffect in order for it to run in every componentDidMount event call.

Also, we need to pass a callback to the function named onAuthStateChanged as an argument as shown in the code snippet below:

useEffect(() => { ............. const subscriber = auth().onAuthStateChanged(onAuthStateChanged); return subscriber; // unsubscribe on unmount }, []);

In the function onAuthStateChanged, we handle local state data as shown in the code snippet below:

function onAuthStateChanged(user) { setUser(user); console.log(user); if (user) setloggedIn(true); }

Now, we need to store the user data for the state. Then, try to display the user’s data after a successful login. For that, we need to use the following piece of code:

{!user && You are currently logged out} {user && (  Welcome {user.displayName}   )}

We will get the following result in our simulator:

result on show auth username

Firebase Sign Out

For signing out, we need to remove all the user’s credentials and revoke the Google sign-in token.

First, we need to wait for the GoogleSignin module to revoke the access and sign out. Then, we call the signOut method of Firebase auth in order to successfully logout.

The overall code implementation is provided in the code snippet below:

signOut = async () => { try { await GoogleSignin.revokeAccess(); await GoogleSignin.signOut(); auth() .signOut() .then(() => alert('Your are signed out!')); setloggedIn(false); // setuserInfo([]); } catch (error) { console.error(error); } };

As a result, we can now perform logout operations as shown in the code snippet below:

firebase react native sign out result

Conclusion

In this tutorial, we learned how to set up Google Login, along with storing an access token, by leveraging Firebase into our React Native project.

First, we created the React Native project with all the necessary components and function configurations. Then, we learned how to configure the Google Sign In and Firebase for both Android and iOS platforms. Finally, we set up the Firebase in React Native app using a Firebase package and displayed the user data along with sign out button.

You can download the complete source code of this tutorial from Github.

The best part is that Firebase & Google Auth are supported across all the mobile development languages, such as Flutter, Swift or Kotlin. The configuration steps and the architectural approach is exactly the same.

Next Steps

Now that you have learned about setting up Firebase Google Login in React Native apps, here are some other topics you can look into:

  • How to Build a React Native App with Firebase Backend
  • Firebase & React Native - Push-meddelelser | Firebase-opbevaring
  • Flere godkendelsesmetoder i React Native & Firebase - Google Login | Facebook-login | Telefon SMS OTP Auth

Hvis du kunne lide denne React Native-tutorial, skal du give mig en stjerne på Github-repoen og dele dette med dit samfund. Du kan tjekke endnu flere gratis React Native-projekter på Instamobile. Skål!