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?)
- 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或其他第三方可以使您的身份驗證過程變得無縫且友好。 用戶不必在注冊過程中浪費時間,這將極大地提高您的注冊和保留率。
- It's safe and secure. 是安全的。
- Users trust Google or Facebook more than an unknown site or app on the Internet. 用戶對Google或Facebook的信任程度超過Internet上的未知站點或應用程序。
- 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 profilewebClientId:'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
:
現在,我們還需要在屏幕上渲染組件。 為此,我們將使用各種組件,例如View
和Button
:
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 = 16compileSdkVersion = 27targetSdkVersion = 26supportLibVersion = "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 newerclasspath 'com.google.gms:google-services:4.1.0' // <--- use this version or newer}
...
allprojects {repositories {mavenLocal()google() // <--- make sure this is includedjcenter()maven {// All of React Native (JS, Obj-C sources, Android binaries) is installed from npmurl "$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 Info → URL 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.
接下來,我們需要將身份驗證配置集成到登錄功能。 成功登錄后,我們將accessToken和idToken存儲到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.
最好的部分是,所有移動開發語言(例如Flutter , Swift或Kotlin)都支持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的知識,那么您可以研究以下其他主題:
How to Build a React Native App with Firebase Backend
如何使用Firebase后端構建React Native應用
Firebase & React Native — ?Push notifications | Firebase storage
Firebase和React Native — 推送通知 | Firebase儲存
More Authentication Methods in React Native & Firebase — Google Login | Facebook login | Phone SMS OTP Auth
React Native和Firebase中的更多身份驗證方法-Google 登錄 | Facebook登錄 | 電話短信OTP身份驗證
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/