Add Google OAuth to the To-Do Client¶
Author: MongoDB Documentation Team
This tutorial walks you through adding the Google OAuth provider to your Stitch app and To-do client(s). The following diagram outlines the OAuth process in a Stitch application:

Time required: 20 minutes
What You’ll Need¶
If you have not yet built the To-do backend, follow the steps in this guide.
If you are building on a previous tutorial, be sure to remove and reinstall node dependencies, so you are working with the most up-to-date SDKs.
Procedure¶
- Android (Java)
- iOS (Swift)
- Web (JavaScript/React)
A. Set up the Backend
There are 2 parts to setting up your Stitch backend app to use Google OAuth with Stitch: you create a Google Oauth client, and then you enable the Google auth provider in the Stitch backend.
For Android apps, you need to create and configure Google OAuth in two different Google tools, Google Cloud Platform and Firebase.
Create a project in GCP¶
Navigate to the Google Cloud Platform (GCP). If you have not yet set up a GCP account, follow the instructions to do so.
Create a new GCP project.
In the project dashboard, click on the menu (upper-left), expand APIs & Services, and then select Credentials. You can also navigate directly to the Credentials page).
Click Create Credentials, and then select OAuth client ID.
Select Web Application, and then:
- Give the application a name
- Add http://mongodb.com in the authorized domains
- Save your changes
In the OAuth client dialog, click OK.
When creating the OAuth client ID:
For Application Type, select
Android
.For Name, enter a name to associate with the client ID.
For Signing-certificate fingerprint, enter the
SHA1
fingerprint. To generate theSHA1
fingerprint, run the following command in a terminal or Windows Command Prompt:Terminal example:
Windows Command Prompt example:
Tip
If using
debug.keystore
, the password isandroid
.Enter the
SHA1
fingerprint. For more information and an example, see Google Setting up OAuth 2.0 Help pageFor Package name, enter the following:
The package name may be found in the
ToDo
Android application project’s AndroidManifest.xmlClick Create.
To create the Web app client credentials, Create credentials, and select OAuth client ID.
For Application Type, select
Web application
.For Name, enter the name you want to associate with this client ID.
For Authorized JavaScript origins, enter the following:
For Authorized redirect URIs, enter the following:
Click Create.
Note the Web app client ID and secret. You will use the information in the Users section of the MongoDB Stitch Admin Console.
Create & Configure an OAuth project in Firebase¶
Navigate to https://console.firebase.google.com/u/0/.
Click :guilabel:
Add Project
, and give the project the same name that you used in the GCP setup steps.Select the 2 checkboxes and then click Create Project.
In the left-hand navigation, click Authentication, and then select the Sign-in Method tab.
Click the Google row, and in the resulting popup, enable Google login, and then save your changes.
Return to the project Overview page (link at the top of the left-hand navigation bar).
Click the Add App button, and then select Android.
Fill in the form with your app’s package name and the debug SHA-1 certificate for your computer.
Note
Refer to https://developers.google.com/android/guides/client-auth for instructions on how to generate your SHA-1 certificate.
A Google services json file is created for you. Download it and copy the file to the root directory of your Android project.
Firebase has also created a GCP client for you. You will now switch back to GCP to get that client’s ID and secret.
Return to GCP (https://console.cloud.google.com/apis/credentials), and you will now see the new credentials that have been created.
In the list of OAuth 2.0 client IDs, find the client labeled Web client (auto created by Google Service), and then click the edit icon ( pencil icon ).
You will use this client ID and client secret when you configure the Google Auth provider in the following steps.
Enable & Configure Google Authentication in Stitch¶
- Navigate to your Stitch application.
- Select Users from the left-side navigation.
- Select the Providers tab.
- For Google, click the Edit button.
- In the Google provider settings:
- Switch the Provider Status toggle to enabled.
- Enter your new Client ID and
- Client Secret from the google Web App client credentials. When entering your secret, you are first prompted to name the secret, and then can paste in the secret value.
- Click Save.
For details on all authentication methods supported by Stitch, see User Authentication Overview.
B. Update your client
For the client work in this tutorial, you can start with the app you built in the previous tutorial or start with an app that already has some of the Android structural work done for you.
Note
If you chose to use your existing app, you will need to create a new layout file and class to handle the logon UI and logic. We recommend you view the pre-configured app for ideas on how this might be structured. The steps in this tutorial assume you are using the pre-configured app.
Get the latest code¶
In the MongoDB Stitch Android tutorial repo, run the following command to fetch the tagged version for this tutorial:
Note that the Android project now includes a LogonActivity.java file and logon.xml layout file. The layout provides the UI for logging in with Google and Facebook OAuth, and the LogonActivity class provides the logic to show the logon activity and handles the authentication.
Add Google Libraries to Gradle¶
Open the project-level Gradle file.
Add the following lines to the
dependencies
:
Update strings.xml¶
Open the
res/values/strings.xml
file.Set the value of the
stitch_client_app_id
key to your Stitch App ID.Add a string key named
google_web_client_id
– or update the existing key – with the Web client ID that was generated during the Google setup process. This is the same ID you used when configuring the Google Auth Provider in your Stitch backend.Important
Counter-intuitively, you specify the Web client ID, not the Android client ID. This is because the final step of authentication against Google comes from the Stitch backend, not the Android app.
With these changes, your strings.xml file might look like this:
Add a button to logon.xml¶
The logon.xml file defines the logon activity layout, which currently only inlcudes a link for logging on anonymously.
At the bottom of the
LinearLayout
, add acom.google.android.gms.common.SignInButton
. Theandroid:id
property should be set to@+id/google_login_button
. Your code may look like the following:
Add logon logic to LogonActivity.java¶
All of the logon logic for this app lives in the LogonActivity class. The Logon activity displays when the app starts, and when a user authenticates (currently only as Anonymous), control is passed to the TodoListActivity. We are now going to add the logic for Google OAuth to the logon activity, so a user can choose to authenticate either as Anonymous or with their Google account.
The first step is to create a method that will encapsulate the Google logon
logic, and then call that method from the existing setupLogin()
method. In
the downloadable app, we have named this function enableGoogleAuth
to follow
the convention we started with the anonymous login code. This method will
instantiate the Google classes needed to send an authorization request to Google
when a user clicks the Google login button that you added to the layout.
Open the LogonActivity.java
file and follow these steps:
In the
enableGoogleAuth
method, you need to create a newGoogleSignInOptions
object by callingbuild()
on aGoogleSignInOptions.Builder
object. Your code should look like this:The
GoogleSignInOptions
object is used to create aGoogleApiClient
, which is the object passed to the Google auth servers when a user authenticates. We have created a_googleApiClient
property, which you need to initialize by using a newGoogleApiClient.Builder
object. Your code should look like this:Now you need to attach an
onClick
hanlder for the button we added to the layout file above. Your code should look like this:Note
The
enableGoogleAuth
method is called when the Logon activity is created.We now need a way to handle the request that comes back from Google. To do this, we’ve created a
onActivityResult
method at the bottom of the class. In this method, add code to make sure the request has come from google by checking that therequestCode
isGOOGLE_SIGN_IN
. If it is, we need to pass the returned information to Stitch for authentication. We want this method to have a single responsibility (handling theonActivityResult
), so we’ll pass the task to a separate method. Your code should look like this:Now we need to add functionality to the
handleGoogleSignInResult()
that we call above. We need to convert the returnedtask
to aGoogleSignInAccount
. TheGoogleSignInAccount
carries the Google server authentication code, which we will send to the Stitch backend:Now that we’ve authenticated against Google, we need to authenticate with Stitch. We already have a static
StitchAppClient
defined in theTodoListActivity
, so we’ll pass the GoogleCredential to theloginWithCredential
method and handle the result of that call. Your code should look like this:
C. Build and Test
You can now run the app (in the emulator or on a device) and see the logon screen with the newly-added Google button. In Android Studio, click the debug icon, or select Debug ‘stitch-tutorial-todo-android’ from the Run menu, and the app is loaded onto the emulator or device you have chosen:
Clicking the button brings up the Google authentication options:
Log in, add some items to your To-do list, and then log out (from the menu). When you log in again with the same account, your to-do list is shown.
A. Set up the Backend
There are 2 parts to setting up your Stitch backend app to use Google OAuth with Stitch: you create a Google Oauth client, and then you enable the Google auth provider in the Stitch backend.
Create a project in GCP¶
Navigate to the Google Cloud Platform (GCP). If you have not yet set up a GCP account, follow the instructions to do so.
Create a new GCP project.
In the project dashboard, click on the menu (upper-left), expand APIs & Services, and then select Credentials. You can also navigate directly to the Credentials page).
OAuth Consent Screen If this is a new project, you may be required to first configure the consent screen.
- Application Type: Should remain public
- Application Name: Can be whatever you wish to call it. We’ve the name Stitch Todo IOS
- Authorized Domains: Add mongodb.com to this field.
- Save your settings.
Create Oauth Credentials for Stitch Now we must create OAuth credentials for Stitch to use. Later in the tutorial we’ll also create credentials for the Todo app itself.
This may seem counter-intuitive or unecessary, but it makes sense when we think about the architecture. Because we want Stitch to manage our users, we must create credentials Stitch can use to comminicate with the Google Identity API.
The flow is as follows:
- The user will login with Google.
- Google will respond with user information, including a special Server Authentication Code used by backend services to verify and manage Google OAuth users in their system.
- The user sends this code to Stitch.
- Stitch sends this code, and uses the web oauth client id and secret to authenticate with Google.
- Google responds with the user’s information.
- Stitch responds to the client with a successful login request.
Click Create Credentials, and then select OAuth client ID.
Select Web Application, and then:
For Application Type, select
Web application
.For Name, enter the name you want to associate with this client ID.
For Authorized JavaScript origins, enter the following:
For Authorized redirect URIs, enter the following:
Click Create.
Note the Web app client ID and secret. You will use the information in the Users section of the MongoDB Stitch Admin Console.
Update the Stitch Backend for Google Authentication¶
- Navigate to your Stitch application.
- Select Users from the left-side navigation.
- Select the Providers tab.
- For Google, click the Edit button.
- In the Google provider settings:
- Switch the Provider Status toggle to enabled.
- Enter your new Client ID and
- Client Secret from the google Web App client credentials. When entering your secret, you are first prompted to name the secret, and then can paste in the secret value.
- Click Save.
For details on all authentication methods supported by Stitch, see User Authentication Overview.
B. Update the iOS Application
Create the iOS OAuth Credentials¶
Now we must create the credentials for our iOS app to use. Navigate to your Google Console Credentials page
Click Create Credentials, and then select OAuth client ID.
Select iOS, and then:
For Application Type, select
iOS
.For Name, enter a name to associate with the client ID.
For Bundle ID, enter your app’s Bundle ID. This can be found in Xcode by selecting the Project from the File Explorer and selecting the General tab.
Click Create.
Modify Podfile
¶
It’s time to jump into Xcode. Open your Todo.xcworkspace
project and
find the Pods
project. Open Podfile
and add the following line
after the line beginning with pod 'StitchSDK', ...
to add support
for Google Signin.
Exit Xcode, and in the project directory run the following command to have Cocoapods add the new dependency,
Once this is complete reopen Todo.xcworkspace
Modify Constants.swift
¶
We will add the constants we need to sign in with Google. We’ll add both the iOS Client ID we created for our iOS app, and we’ll add the Client ID we created for our web app for Stitch to use.
Add the following to the bottom of Constants.swift
prior to the
closing brace of the Constants struct.
Modify AppDelegate.swift
¶
Now it’s time to modify AppDelegate.swift
to allow our application
to support signing in with Google.
First, add the following import right after the line import StitchRemoteMongoDBService
.
Next, declare that class AppDelegate
conforms to the GIDSignInDelegate
protocol by added it to the declaration list.
Replace the following line:
With the following:
Now it’s time to set up the Google Sign In instance. Within the lifecyle function didFinishLaunchingWithOptions, add the following code before the window set-up logic.
Now we must add the required methods to conform to the GIDSignInDelegate protocol. Add the following code.
sign
will be called after the user grants permission through Google
to our application. If there was an error, we immediately exit.
Otherwise, we proceed and inspect the serverAuthCode. In testing, we
found behavior for receiving this code to be a bit surprising. If the
user is already signed in to our application, serverAuthCode will be
nil
.
It is important to always call GIDSignIn.sharedInstance().signOut()
in any error case and when the user signs out of the application.
We initialize a GoogleCredential with the serverAuthCode, and
check the result. If everything works, we post a notification of the
event to be handled elsewhere in the app. If not, we print out an error
message and call GIDSignIn.sharedInstance()?.signOut()
Modify WelcomeViewController.swift
¶
In the previous version of this application where we only supported Anonymous Login, we were using an AlertController to log in. This worked for our needs then, but now we’d like to show the Google Sign In button.
We also need to add this view controller as a listener to the NotificationCenter
for “OAUTH_SIGN_IN” events in order to move our view flow forward to
the TodoTableViewController
.
Replace the entire contents of WelcomeViewController.swift
with the following:
Modify TodoTableViewController.swift
¶
We’re almost finished, only a few items remaining! We need to modify
our logout functionality in TodoTableViewController
. We’ll add a
check to determine whether the user was logged in with Google. If so,
we’ll call the GIDSignIn.sharedInstance()?.signOut()
method. To do
this, we’ll also make sure to import GoogleSignIn
.
Add the following import to the top of the file:
Now, modify your logout function to match the following:
Add URL Types Information¶
The last thing we need to do is allow our application to call the Google OAuth URL for our iOS client.
To do this, navigate to your Google Cloud Credentials page and select your iOS credentials.
Copy the value of iOS URL scheme, which is your Client ID in reverse order.
In Xcode, select the Todo
project from the Project Navigator, and
select the Info tab. Find the URL Types section, click the +
and paste the value you copied above into the the URL Schemes area.
Leave Editor as the selected role.
C. Build and Test
- You can now run the app (in the emulator or on a device) and see the logon screen with the newly-added Google button:
- Log in, add some items to your To-do list, and then log out (from the menu). When you log in again with the same account, your to-do list is shown.
There are two parts to setting up your Stitch backend app to use Google OAuth with Stitch: you create a Google OAuth client, and then you enable the Google auth provider in the Stitch backend.
A. Set up the Backend
Your first step here is to set up the backend of your application. First, you need to create a Google Cloud Project that will handle user authentication. Then, you must configure the Google OAuth provider in the Stitch backend, so your app can receive and understand the user authenticaiton from the GCP.
Create a project in GCP¶
Navigate to the Google Cloud Platform (GCP). If you have not yet set up a GCP account, follow the instructions to do so.
Create a new GCP project.
In the project dashboard, click on the menu (upper-left), expand APIs & Services, and then select Credentials. You can also navigate directly to the Credentials page).
OAuth Consent Screen: If this is a new project, you may be required to first configure the consent screen.
- Application Type: Should remain public
- Application Name: Can be whatever you wish to call it. We’ve named ours Stitch Todo Web
- Authorized Domains: Add mongodb.com to this field.
- Save your settings.
Create Oauth Credentials for Stitch: Now we must create OAuth credentials for Stitch to use. Later in the tutorial we’ll also create credentials for the To-do client application.
This may seem counter-intuitive or unnecessary, but it makes sense when we think about the architecture. Because we want Stitch to manage our users, we must create credentials Stitch can use to communicate with the Google Identity API.
The flow is as follows:
- The user logs in with Google.
- If the user successfully logs in, Google returns the user to the client app with a server auth code in the URL (redirect result).
- The user sends this code to Stitch.
- Stitch uses this code alongside the Web OAuth Client ID + Secret to authenticate with Google on the user’s behalf.
- Google responds with the user’s information.
- Stitch responds to the client with a successful login request.
Click Create Credentials, and then select OAuth client ID.
Enter the following information to create credentials:
For Application Type, select
Web application
.For Name, enter the name you want to associate with this client ID.
For Authorized JavaScript origins, enter the following:
For Authorized redirect URIs, enter the following:
Click Create.
Note the Web app client ID and secret. You will use the information in the Users section of the MongoDB Stitch Admin Console.
Update the Stitch Backend for Google Authentication¶
- Navigate to your Stitch application.
- Select Users from the left-side navigation.
- Select the Providers tab.
- For Google, click the Edit button.
- In the Google provider settings:
- Switch the Provider Status toggle to enabled.
- Enter your new Client ID.
- Create a new Secret in the Client Secret box. You will first be prompted to enter a secret name. Then, paste in the secret value from the google Web App client credentials.
- Note the Redirect URIs section. You do not need to update this section yet, but will revisit it in step 3 of this tutorial.
- Click Save.
Deploy Your Changes
Before moving on, be sure to Review and Deploy Changes to your Stitch app. You can do this by clicking the button in the blue bar at the top of your screen, or by clicking Deploy in the left sidebar.
For details on all authentication methods supported by Stitch, see User Authentication Overview.
B. Update Web Application
Now that you’ve established commmunication between the Stitch backend and your GCP, it’s time to edit the React and Stitch portions of the client web app to use the authentication you’ve just set up.
Add a Stitch Authentication Event Listener¶
In this section, you will alter the pre-existing React code for anonymous login to be compatible with Google OAuth. Namely, you will set up an event listener to determine when login occurs. The Stitch Browser SDK allows you to set up event listeners that can automatically respond to authentication events in your client application, such as when a user logs in or out.
Add the following two functions to
stitch/authentication.js
. These two functions add and remove listeners, resepctively, based on a providedlistener
argument. You will build one such listener in the upcoming steps and will then better understand its structure.Now that you can add and remove authentication listeners, you need to actually create a listener object and add it in the React code. Add
addAuthenticationListener
andremoveAuthenticationListener
to your import fromstitch/authentication.js
inStitchAuth.js
:Once you’ve imported the functions, you can use React’s effect hook to add the authentication listener when the app first loads and remove the listener when the app unmounts or the user navigates away. Before you can use the hook, import
useEffect
from React. This is what the very first line ofStitchAuth.js
should look like after doing so:Now that
useEffect
has been imported, add the following code block directly above thehandleAnonymousLogin
function inStitchAuth.js
:In the exisiting code, there is a
handleAnonymousLogin
function that (as its name implies) is specific to anonymous login. In this step, you will create the more generichandleLogin
function, which will allow us to use multiple auth providers. Replace the entirehandleAnonymousLogin
function with the following:Now that
handleAnonymousLogin
no longer exists in your code, you need to change existing calls to it. Scroll down inStitchAuth.js
until you find theauthInfo
function. In the line beginning with “actions”, changehandleAnonymousLogin
tohandleLogin
. The result should look like this:Finally, alter the “Anonymous Login” button to call
handleLogin
when clicked, instead ofhandleAnonymousLogin
. Modify theonClick
handler as follows:At this point, your anonymous login should work exactly as it did before. Now you’re ready to add login functionality for other authentication providers.
Add Google OAuth Functions¶
Your next step in adding Google OAuth functionality is to write
a loginGoogle
function. The main difference between
loginAnonymous
and the
loginGoogle
function that you are about to write is the use
of loginWithCredential
vs loginWithRedirect
.
Some types of authentication, like Anonymous, use
loginWithCredential
, which means
that it uses a regular Stitch credential to authenticate the
user. The Google OAuth 2.0 provider, on the other hand, redirects the user
away from the current page to a page owned by Google where the user
authenticates. Upon successful authentication, Google returns the user
to the original page with a token that proves their identity. The Stitch
SDK uses the token to construct a redirect credential and log the user
in.
Before you can invoke
loginWithRedirect
in theloginGoogle
function, you must addGoogleRedirectCredential
to your import frommongodb-stitch-browser-sdk
:In the same file, add the following
loginGoogle
function.Now that you’ve written your
loginGoogle
function, you must add it tohandleLogin
. Before you can do this, you must first import the function toStitchAuth.js
. AddloginGoogle
to your import fromstitch/authentication.js
Recall that
handleLogin
is meant to handle login across multiple auth providers. In this step, you will give the function the ability to handle login with Google OAuth. Navigate toStitchAuth.js
, and add the following line of code within theswitch
statement in thehandleLogin
function.The final step is to create a button to provide the user with the option to login with Google. This button is similar to the anonymous login button, but when clicked, it passes
"google"
as the argument tohandleLogin
. Copy and paste the following React code for the Google login button immediately below the code for the Anonymous button:
Handle Google Redirects¶
It may seem as though you now have all pieces needed to log in with Google. Try running your app to see what happens. You’ll notice that when you click the “Log In with Google” button, you get an error. This happens because you haven’t actually handled redirects with Google yet. You’ll address these in the upcoming steps.
The first change you need to make is in your Stitch application. In this step, you will add a redirect URI to the Stitch backend. This how you “approve” a specific URL which lets Stitch know that it’s safe to redirect back to a specific domain.
Select Users from the left-side navigation.
Select the Providers tab.
For Google, click the Edit button.
In the Google provider settings, add the following to the Redirect URIs section:
Note
Port 3000 is the default port on which your app will run. However, if you notice your app is running on a different port, update the port number in the above URI accordingly.
Deploy Your Changes
Again, make sure to Review and Deploy Changes to your Stitch app by clicking either the button in the blue bar at the top of the screen, or the Deploy button in the left sidebar.
Although the
loginGoogle
function uses redirect credentials, your app currently has no way of knowing when an external login has redirected the user back to the app, and thus, does not actually log the user into the app. In this step, you will add thehandleOAuthRedirects
function, which checks that the user has returned to the app, and then completes the OAuth login. Copy the function below intostitch/authentication.js
.Import
handleOAuthRedirects
for use in yourStitchAuth.js
file. Add the highlighted line to your import fromstitch/authentication.js
:Finally, in
StitchAuth.js
, add a call tohandleOAuthRedirects
right after the call toaddAuthenticationListener
within the effect hook.
C. Build and Test
- You can now run the app and see the logon screen with the newly-added Google button.
- Log in, add some items to your To-do list, and then log out (from the menu). When you log in again with the same account, your to-do list is shown.
Summary¶
Congratulations! You now have a working to-do app that includes Google authentication.