Integrate Google Login in React Native apps (iOS) with Firebase
In this post, we’ll learn how to setup Google Login in React Native apps using Firebase. We’ll implement the authentication using react-native-google-signin
npm package, and then test it on iOS.
I have another blog explaining how to implement Google Login in React Native for Android, using Firebase.
Complete source code of this tutorial is available here — React-Native-google-login
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
Authentication in React Native
React Native has been around for around 4 years, and has been very popular among developers for its ease of usage over Swift / Java. Also you get to keep a single source code for both Android and iOS app. What more can a developer ask for!
React Native 0.60 is the latest version (at the time of writing this post), and is much more reliable and robust than previous versions. It also includes breaking changes related to AndroidX, but don’t worry we’ll create an Android test app as well.
There are several ways of Authentication in React Native Apps
- Social logins — Social logins are a popular and easy way of authentication in mobile apps. You must have seen Google, Facebook, Instagram logins in almost all the modern apps. Social logins are easy to use and more reliable for quick integrations.
- Create you own back-end — You can create your own back-end in Node.js, Go, Django or Ruby-on-rails, and connect your app authentication to your own back-end. This method is favored by developers who need full control over the user authentication. But this method is the most time taking one as well.
- Back-end as a Service (BaaS) — You can use pre-built BaaS platforms which allows easy integration of authentication in your apps. Basically, these platforms provide you a ready-made back-end, so you don’t have to make one on your own. Firebase, Parse, Back4App are some BaaS platforms.
Firebase is the most popular among these for mobile apps, which we’ll study in next section
Firebase
Firebase is a Backend-as-a-Service (BaaS) platform. It started as a YC11 startup and grew up into a next-generation app-development platform on Google Cloud Platform. It is getting popular by the day because of the ease of integration and variety of functionalities available on it.
A lot of quick integrations are available with Firebase. Some of these are listed below:
- Real-time database
- Email Authentication
- Social logins
- In-app messages
- Push notifications
- Analytics
- Crashlytics
- Remote config
Firebase is quickly growing to become the most popular mobile app back-end platform.
Firebase Authentication Options
Firebase not only provides ready-made email authentication, but also provides authentication using a variety of social logins. You can see the authentication options available with Firebase
We will use Firebase to store user profile information once the Google login is done. This is the preferred method, as it is reliable for both apps and PWA.
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 your Platforms
Step 2: Enable Google Sign-In in Firebase project
Step 3: Create a Basic React Native app
Step 4: Install the react-native-google-signin
package for Google Login
Step 5: Implement Google auth functions in RN app
Step 6: Test your app on iOS
Step 7: Use Firebase to auto-login the user
So let’s jump right in
Step 1: Create Firebase Project
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.
1.1 If you don’t have an existing Firebase Project
If you already have a Firebase project, skip to step 1.2. Otherwise, create a new Firebase project by going toFirebase Console. Give your project a name and that’s it !
1.2 Create and attach new app to the project
Now that the project is created, create a new app in the project dashboard.
First, let’s create an iOS app and attach it to the project
Just mention the correct bundle_id
of your app in the iOS bundle ID
input. Give it a nickname to remember.
Next step, download the GoogleService-Info.plist
file and put it in the root of your iOS project folder. You can skip rest of the steps for now. Your app is created now, and you should see it in the dashboard.
Step 2: Enable Google Login in Firebase
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 the Enable
toggle.
Give a name to for your Auth consent screen and save your web client Id as well. This will be used to integrate the React Native app with Firebase.
We will also need areversed_client_id
, but that we can get from the GoogleService-Info.plist
file you just downloaded in above step. This reversed_client_id
can also be obtained from Google developer console, but let’s not get into that for now.
Step 3: Create a basic React Native app
First, make sure you have all pre-requisites to create a react-native app as per the official documentation.
At the time of this post, I have React-Native version 0.60
Create a blank react-native app (Replace myApp
with your own name)
$ react-native init RNGoogleLogin
This will create a basic React-native app which you can run in a device or simulator. (let’s first run iOS)
Let’s run the app in iOS using (I’m using emulator)
$ react-native run-ios
You’ll see the default start screen
Change the UI of this front page by changing app.js
and the page will look like this. (The Google login button here actually comes after the package integration, as explained in next section)
Step 4: Install the package for Google Login
To enable Google Login, we’ll install a package named react-native-google-signin. This is a widely used package for Google Login, and also very reliable.
Install package
Install the package using
$ yarn add react-native-google-signin
Link the package with your platforms using
$ react-native link react-native-google-signin
Add Google Auth SDK to iOS platform
This is usually done using Pods. Pods are package manager for iOS project, similar to yarn
or npm
for Javascript projects. Pod file is found in your iOS project’s root.
Open the podfile with any text editor, add pod 'GoogleSignIn', '~> 4.4.0'
in your Podfile and run pod install
Note: If you don’t have a Podfile, follow these instructions:
1 . pod init
creates a Podfile.
2 . add GoogleSignIn
pod (see example below)
3 . run pod install
4 . from now on, use Xcode to open the <your project>.xcodeworkspace
file (do not open the .xcodeproj
any more)
Sample Podfile
# Uncomment the next line to define a global platform for your project # platform :ios, '9.0'
target 'test_google_signin' do # Uncomment the next line if you're using Swift or would like to use dynamic frameworks # use_frameworks!
# Pods for test_google_signin pod 'GoogleSignIn', '~> 4.4.0' // RNGoogleSignin requires GoogleSignIn >= 4.3.0
target 'test_google_signin-tvOSTests' do inherit! :search_paths # Pods for testing end
target 'test_google_signinTests' do inherit! :search_paths # Pods for testing end
end
At the end, the dependencies should be linked like in this picture
Also notice that GoogleServiceInfo.plist is added to resources. If you don’t see it here, click the + button in Copy Bundle Resources
section, and add the file.
XCode configuration
In XCode, add your REVERSED_CLIENT_ID
(found inside GoogleService-Info.plist
) to the URL schemes as shown below
If you are having issues with Pod install, Xcode configuration or if you have more than one social login in the app, check further details here
Now your iOS project is all set to connect to Firebase and Google Login. Notice that at this point, we are using Firebase only as a way to create a Google Project and obtain web_client_id
and reverse_client_id
. We haven’t yet connected Firebase with the app, as such. We will do that later in another section.
Step 5: Implement Google auth functions in RN app
Now that the app is all connected to Google Auth, let’s write the actual code to call login / logout etc functions.
First of all, I have created a separate file LoginController.js
and imported it in App.js
, just to maintain a good code structure.
My App.js
looks like following (nothing fancy, I’m not even gonna waste a gist here)
import React, { Fragment } from 'react'; import LoginController from './LoginController';
const App = () => {return (<LoginController/>);}; export default App;
Yes, that’s it 😆
5.1 Implement Google Login button
In the LoginController.js
, I add Google login button using following code
import { GoogleSignin, GoogleSigninButton, statusCodes } from 'react-native-google-signin';
.....(inside render) <GoogleSigninButton style={{ width: 192, height: 48 }} size={GoogleSigninButton.Size.Wide} color={GoogleSigninButton.Color.Dark} onPress={this._signIn} disabled={this.state.isSigninInProgress} /> ....
This shows the beautiful Google Button as per their marketing guidelines
5.2 Configure Sign In on App start
Before calling signIn
method, we need to call configure
method, which sets the parameters for Google Auth. You can call this method in componentDidMount
GoogleSignin.configure({
scopes: ['https://www.googleapis.com/auth/drive.readonly'], webClientId: 'XXXXXX-qXXXXXn7umiXXXXXXe1ekgubrXXe.apps.googleusercontent.com', offlineAccess: true, hostedDomain: '', loginHint: '', forceConsentPrompt: true, accountName: '', iosClientId: 'XXXXXX-krv1hjXXXXXXp51pisuc1104q5XXXXXXe.apps.googleusercontent.com' });
Let’s look at this in more detail
- scopes: This tell what API you want to access on behalf of the user, leave it blank for just email and profile access. For more API access, you might have to get your app verified, or you’ll see this warning when logging in
- webClientId: Client ID of type WEB for your server needed to verify user ID and offline access. This is what we copied from Firebase console in Step 2
- offlineAccess: If you want to access Google API on behalf of the user from your server
- hostedDomain: Specifies a hosted domain restriction for auth
- loginHint: Only for iOS - The user’s ID, or email address, to be prefilled in the authentication UI if possible. (See docs here)
- forceConsentPrompt: Only for Android — if you want to show the authorization prompt at each login.
- accountName: Only for Android — Specifies an account name on the device that should be used
- iosClientId: Only for iOS — Optional, if you want to specify the client ID of type iOS (otherwise, it is taken from
GoogleService-Info.plist
). Of course, if you omit this, yourGoogleService-Info.plist
needs to be correctly configured in XCode.
5.3 Sign In Method
The signIn
method called from the Google Login button goes like this
The userinfo
is saved in the state and hence can work to take user to next page, or change elements in the same page. For the sake of simplicity, I won’t put in another page and trouble you with concepts of routing. Instead, we’ll just change the elements of our homepage when user gets logged in. Sounds fair ? Cool !
5.4 Sign Out Method
The sing out method looks like this
5.5 Silent login
When user logs in once, on next app start you don’t want user to login again. Hence you try to silently login the user. If user is already logged in and has a valid session, the user will silently login. You can call this method as well in componentDidMount
. Remember to call configure
method before this as well. If the user does not have a valid session, this method will return null
and you can ask user to sign in
There are more methods like isSignedIn()
, getCurrentUser()
, getTokens()
etc, whose details you can get on the package’s Github.
Overall, my LoginController.js
file looks like this (a bit long, I know)
Step 6: Test your app on iOS
Let’s now build the app for iOS. I am using a simulator, but you can always use a real device as well.
Run the app on iOS simulator using
$ react-native run-ios --simulator="iPhone 8"
or simply on a connected device (or default simulator) using
$ react-native run-ios
Here’s how my Google Login app works
Note : If you have more scopes than just basic info, you’ll see an App Not Verified
screen. You can skip the warning and still login. But that warning won’t look good to your user. You might consider getting your app verified if you get that warning.
UserInfo
After login, here’s how my user data looks like in essence
I have arranged this in the LoginController.js
in a list format for better UI.
Step 7: Use Firebase to auto-login the user
We have seen above that using “Silent Login”, we can login the user silently. Also, notice that we haven’t connected Firebase directly to our app till now, and still managed to login using Google. That’s why the Firebase user table is still empty
We only used Firebase for
- Creating a Google project
- Obtaining
web_client_id
andreversed_client_id
Both of which can be done in Google Developer Console as well, without touching Firebase.
So why do we need to attach Firebase at all ?
- Well, we don’t need to. If you have an app, you’re probably going to have a back-end with it as well. Generally we store auth credentials like token and ID in back-end, so the server can authorize access based on valid sessions. In case you are using Firebase as a back-end for your app (which is a great choice btw), you can attach Firebase to Google Login, and store the
token
anduserID
in Firebase. This way, Firebase will take care of your user sessions. - If you have more than one login methods e.g. Facebook login, direct email login, you would like to have the control in single place. Firebase is perfect for such a situation.
- Storing user info in Firebase is useful for analytics and so many other purposes, rather than having the info just in the user’s app.
- And because you can ! 😎
Connect Firebase to your React Native app using react-native-firebase
react-native-firebase
is a popular package to connect React Native apps to Firebase various functionalities.
React-native-firebase also recommends using react-native-google-signin
for Google authentication, which we just used above.
- To connect it to your app, make sure the
GoogleService-Info.plist
file to your iOS app using ‘File → Add Files to “[YOUR APP NAME]”…’ in XCode, as shown in the screenshot below
- Install
react-native-firebase
package using
$ npm install --save react-native-firebase
This installs the package, but it still needs to be connected to XCode properly
Modify Xcode files
To initilize the native SDK in your app, add the following to your ios/[YOUR APP NAME]/AppDelegate.m
file:
#import <Firebase.h>
Also, at the beginning of the didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
method add the following line:
[FIRApp configure];
Install required Pods
Open your pod file in iOS root folder and add two dependencies
pod 'Firebase/Core', '~> 6.3.0'
pod 'Firebase/Auth', '~> 6.3.0'
Runpod install
to install the dependencies. If you face an error of versions, try running pod repo update
and then run pod install
Link the react-native-firebase package with iOS platform
Link the react-native-firebase package with iOS platform using
$ react-native link react-native-firebase
However, from RN ≥0.60, you don’t need to manually link packages. It is done automatically when packaging the platform for build.
Changes in LoginController.js
Now that we are going to save the login info in Firebase, we’ll call a Fierbase method to store the required data in back-end. Following function logs the user in , and then saves the info in Firebase
Note, firebase.auth().signInWithCredential
is the method used to store user credentials in back-end.
Now, run the app again using CLI or XCode, log in as usual and you’ll see that a user pops up in Firebase Users list
You have successfully
- Logged in a user using Google Login in React Native
- Attached the authentication to Firebase to store user credentials
🎉 🎉 🎉 🎉 🎉 🎉 🎉
Firebase, further
You can now go ahead and attach more Firebase functions like logout, silent login, userinfo etc. since you have user credentials in Firebase.
Note, not all userInfo that we receive after Google Login gets stored in Firebase by default. If you want all the information to be stored, then you should use the FireStore database to store it, and retrieve it when required.
For more details on functions like
- CRUD operations in Firestore
- Image Upload
- Phone authentication
check out this blog.
Conclusion
In this blog, you learnt how to implement Google Login in React Native apps. You also learnt how to attach this authentication to Firebase for better handling using back-end. We also built the app in iOS and ran on a simulator.
Complete source code of this tutorial is available here — React-Native-google-login