如何在React Native和Firebase中设置Google登录

Google sign-in is a great login feature to offer to your app's users. It makes it easier for them to create an account and sign in.

Google登录是一项出色的登录功能,可为您的应用程序用户提供。 这使他们更容易创建帐户并登录。

And what's even better, Firebase makes it extremely easy for developers to add support for Google sign-in. But setting up the React Native environment can create some challenges, which are fully covered in this tutorial.

更妙的是,Firebase使开发人员添加Google登录支持变得非常容易。 但是设置React Native环境可能会带来一些挑战,本教程将全面介绍这些挑战。

React Native and Firebase SDK make the implementation of Google login pretty straightforward. Let's build a simple app that only has a single Google login button. Once the user successfully logs into Google, we are going to display the user info retrieved from their Google account as well as a logout button.

React Native和Firebase SDK使Google登录的实现非常简单。 让我们构建一个只有一个Google登录按钮的简单应用。 用户成功登录Google后,我们将显示从其Google帐户检索到的用户信息以及注销按钮。

You can also add Facebook Login to your app if you're interested in providing even more login options to your users. You can check out this guide to Facebook Login in React Native with Firebase if you're looking to learn more on how to set up Facebook sign-in.

如果您有兴趣向用户提供更多登录选项,也可以将Facebook Login添加到您的应用程序。 如果您想了解有关如何设置Facebook登录的更多信息,可以查看本指南中的使用Firebase在Fire Native中进行 Facebook登录。

为什么要在移动应用中使用Google登录按钮? (Why Use a Google Sign-in Button in Mobile Apps?)

  1. Using Google or other third parties can make your authentication process seamless and friendly. Users don’t have to waste time in the registration process, which will improve your registration and retention rates tremendously.

    使用Google或其他第三方可以使您的身份验证过程变得无缝且友好。 用户不必在注册过程中浪费时间,这将极大地提高您的注册和保留率。
  2. It's safe and secure.

    是安全的。
  3. Users trust Google or Facebook more than an unknown site or app on the Internet.

    用户对Google或Facebook的信任程度超过Internet上的未知站点或应用程序。
  4. It provides a good user experience. As a user, we have little patience for any actions or work that we need to do, especially in a fairly unknown app that we are trying for the first time.

    它提供了良好的用户体验。 作为用户,我们对需要执行的任何操作或工作几乎没有耐心,尤其是在我们首次尝试的未知应用程序中。

Without further ado, let's jump directly into the app development part of this tutorial.

事不宜迟,让我们直接进入本教程的应用程序开发部分。

设置Firebase项目 (Setting up the Firebase Project)

Go to the Firebase Console and create a Firebase project:

转到Firebase控制台并创建一个Firebase项目:

Here, we will need to set up the Firebase project name and app identifier, so let's first create the React Native app.

在这里,我们将需要设置Firebase项目名称和应用程序标识符,因此让我们首先创建React Native应用程序。

创建React Native项目 (Creating the React Native Project)

First, we need to create a React Native project by using the following command:

首先,我们需要使用以下命令创建一个React Native项目:

react-native init instamobile-google-login-demo

react-native init instamobile-google-login-demo

H‌ere, we have given the name of the project as instamobile-google-login-demo. Now, we need to install the react-native-google-signin package using the following command:

‌,我们将项目的名称命名为instamobile-google-login-demo 。 现在,我们需要使用以下命令安装react-native-google-signin软件包:

yarn add react-native-google-singin

yarn add react-native-google-singin

The react-native-google-signin package is used to implement Google auth functions in the React Native app. Now, we need to import the necessary modules and components from the respective package as shown in the code snippet below:

react-native-google-signin软件包用于在React Native应用程序中实现Google auth功能。 现在,我们需要从相应的包中导入必要的模块和组件,如下面的代码片段所示:

Next, we need to create the states in order to handle the auth state and user info. For that we use the useState module as shown in the code snippet below:

接下来,我们需要创建状态以处理身份验证状态和用户信息。 为此,我们使用useState模块,如下面的代码片段所示:

Now, we need to create a sign-in function to handle authentication as shown in the code snippet below:

现在,我们需要创建一个登录功能来处理身份验证,如下面的代码片段所示:

Next, we need to initialize the setup of the Google login object by leveraging the useEffect function:

接下来,我们需要利用useEffect函数来初始化Google登录对象的设置:

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
   });
 }, []);

Lastly, we need a function that handles the logout action. For that, we are going to implement the signOut method as shown in the code snippet below:

最后,我们需要一个处理注销操作的函数。 为此,我们将实现signOut方法,如下面的代码片段所示:

Now, we need to render the components on the screen as well. For that, we are going to make use of various components like View and Button:

现在,我们还需要在屏幕上渲染组件。 为此,我们将使用各种组件,例如ViewButton

Now, if we run our project in the emulator we will get the following results:

现在,如果我们在仿真器中运行项目,我们将得到以下结果:

Pretty sweet, right? We have completed the implementation (both UI and business logic) at the React Native level in our project.

很漂亮吧? 我们已经在项目的React Native级别完成了实现(UI和业务逻辑)。

As you can see, we have a "Sign in with Google" button that converts into a logout button once the login operation is successfully completed.

如您所见,我们有一个“使用Google登录”按钮,一旦成功完成登录操作,该按钮就会转换为注销按钮。

We are now going to set up the Google SignIn package and the Firebase app.

现在,我们将设置Google登录包和Firebase应用。

配置iOS和Android本机项目 (Configuring the iOS and Android Native Projects)

There are a few set up steps we need to take before the project is fully working. They are mostly related to the actual native side of the app.

在项目全面运行之前,我们需要采取一些设置步骤。 它们主要与应用程序的实际本机方面有关。

对于iOS (For iOS)

Here, in VSCode (or any Terminal)  just run cd ios && pod install. Then open the .xcworkspace file in Xcode (from the ios folder) and make sure the Pods are included:

在这里,在VSCode(或任何终端)中,只需运行cd ios && pod install 。 然后在Xcode(从ios文件夹)中打开.xcworkspace文件,并确保包含Pod

对于Android (For Android)

1. First, we need to link the native module.

1.首先,我们需要链接本机模块。

  • In RN >= 0.60 you should not need to do anything thanks to auto-linking.

    在RN> = 0.60中,由于自动链接,您无需执行任何操作。
  • In RN < 0.60 run react-native link react-native-google-signin.

    在RN <0.60中,运行react-native link react-native-google-signin

2. Update android/build.gradle with the following configuration:

2.使用以下配置更新android / build.gradle

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. Update android/app/build.gradle with the following configuration:

3.使用以下配置更新android/app/build.gradle

...
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
}

Check that react-native link linked the native module – but only if you used react-native link!

检查react-native link链接了本机模块,但仅当您使用react-native link时才检查!

In android/settings.gradle  we should have the following configurations:

android/settings.gradle我们应该具有以下配置:

Next, in MainApplication.java , we should have the Google package added as in following code snippet:

接下来,在MainApplication.java ,我们应该添加Google包,如以下代码片段所示:

设置Firebase (Setting up Firebase)

对于iOS (For 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.

现在,我们需要开始Firebase配置。 在Firebase中,我们需要设置一个Google云应用。 但是,当我们在Firebase上设置身份验证方法时,这也会创建一个Google云应用。

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

首先,我们需要创建Firebase iOS应用以获取GoogleServiceinfo.plist ,如以下屏幕截图所示:

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

接下来,我们将GoogleService-info.plist文件复制到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:

现在,我们需要将存在于GoogleService-info.plist文件中的反向客户端ID添加到URL类型,如以下屏幕截图所示:

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

下一步是转到信息URL类型,然后填写URL方案 ,如下面的屏幕快照所示:

对于Android (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:

首先,我们需要在Firebase上创建一个Android应用。 为此,我们需要应用程序中的软件包名称和证书SHA-1 。 然后,我们可以如下所示注册Firebase应用程序:

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

我们可以在我们项目的MainApplication.java中获得包名称,如下面的代码片段所示:

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

接下来,我们可以在密钥库文件中获取SHA-1密钥。 在android / app目录中,我们可以运行以下命令:

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

然后,将显示SHA-1键,如下面的屏幕截图所示:

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:

成功创建Firebase设置应用后,我们需要下载google-services.json文件并将其复制到目录,如以下屏幕截图所示:

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

现在,最后一步是在Android中设置Google登录组件。

安装React Native Firebase软件包 (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:

为了安装react-native-firebase软件包版本6,我们需要在项目命令提示符下运行以下命令:

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

在使用任何其他Firebase服务之前,必须先安装@react-native-firebase/app模块。

对于iOS (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.

我们已经将GoogleService-Info.plist添加到Xcode。 剩下的就是允许iOS上的Firebase使用凭据。 必须在应用程序的引导阶段配置Firebase iOS SDK。

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

为此,我们需要打开/ios/{projectName}/AppDelegate.m文件,并添加以下内容:

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

在文件顶部,我们需要导入Firebase SDK:

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

在您现有的didFinishLaunchingWithOptions方法中,我们需要在该方法的顶部添加以下内容:

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

最后,我们需要运行以下命令来完成CocoaPods软件包的安装:

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

而已。 现在,我们已经完成了iOS上主要Firebase软件包的安装

对于Android (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.

我们需要使用Android凭据配置Firebase。 要允许Android上的Firebase使用凭据,必须在项目上启用google-services插件。 这需要修改Android目录中的两个文件。

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

首先,将google-services插件添加为android / build.gradle文件中的依赖

React Native Firebase身份验证模块 (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:

安装完成后,我们需要设置父级Firebase软件包。 接下来,我们需要安装子模块进行身份验证。 为此,我们需要打开一个终端并运行以下命令:

对于iOS (For iOS)

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

我们只需要在命令提示符下再次安装Pod:

对于Android (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.

您可以按照官方文档上的说明进行操作,仅在使用React Native <= 0.59或需要手动集成库时才需要。

在Firebase上激活Google登录 (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:

我们需要转到Firebase控制台。 然后,在“身份验证”部分中,我们需要单击Google,如以下屏幕截图所示:

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

接下来,我们需要使用以下配置启用设置并保存配置,如下面的屏幕快照所示:

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

App.js中 ,我们需要从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.

接下来,我们需要将身份验证配置集成到登录功能。 成功登录后,我们将accessTokenidToken存储到Firebase。 现在,我们可以尝试在演示的React Native应用上使用Google登录。

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

现在,我们已经成功完成了在我们的React Native应用程序中Google登录的集成:

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

我们可以看到添加到Firebase控制台的新数据:

跟踪用户状态 (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.

为了检查用户的登录状态,我们使用Firebase Auth。 为此,我们需要将onAuthStateChanged方法添加到useEffect ,以便使其在每个componentDidMount事件调用中运行。

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

另外,我们需要将回调传递给名为onAuthStateChanged的函数作为参数,如下面的代码片段所示:

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

onAuthStateChanged函数中我们处理本地状态数据,如下面的代码片段所示:

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:

现在,我们需要存储该状态的用户数据。 然后,尝试在成功登录后显示用户的数据。 为此,我们需要使用以下代码:

We will get the following result in our simulator:

我们将在模拟器中得到以下结果:

Firebase注销 (Firebase Sign Out)

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

要注销,我们需要删除所有用户的凭据并撤消Google登录令牌。

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.

首先,我们需要等待GoogleSignin模块撤消访问权并退出。 然后,我们调用Firebase auth的signOut方法以成功注销。

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

以下代码段提供了总体代码实现:

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

结果,我们现在可以执行注销操作,如下面的代码片段所示:

结论 (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.

在本教程中,我们学习了如何通过将Firebase利用到我们的React Native项目中来设置Google登录以及存储访问令牌。

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.

首先,我们创建了具有所有必要组件和功能配置的React Native项目。 然后,我们学习了如何为Android和iOS平台配置Google登录和Firebase。 最后,我们使用Firebase软件包在React Native应用程序中设置了Firebase,并显示了用户数据以及“退出”按钮。

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

您可以从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.

最好的部分是,所有移动开发语言(例如FlutterSwiftKotlin)都支持Firebase和Google Auth。 配置步骤和体系结构方法完全相同。

下一步 (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:

既然您已经了解了在React Native应用程序中设置Firebase Google Login的知识,那么您可以研究以下其他主题:

If you liked this React Native tutorial, please give me a star on the Github repo and share this with your community. You can check out even more free React Native projects on Instamobile. Cheers!

如果您喜欢这个React Native教程,请给我一个Github存储库上的星星,并与您的社区分享。 您可以在Instamobile上查看更多免费的React Native项目 。 干杯!

翻译自: https://www.freecodecamp.org/news/google-login-with-react-native-and-firebase/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值