Add Google OAuth to the To-Do Client¶

锺离珂
2023-12-01

MongoDB Logo
ServerDriversCloudToolsGuides
Get MongoDB
Close ×
MongoDB Stitch

Introduction
Tutorials
    Overview
    Basic Blog Tutorial
        Blog App Overview
        Build the Blog Backend
        Build a Web-based Blog Client
    To-Do App Tutorial
        To-do App Overview
        Build the To-do Backend
        Build a To-do Client
        Add Google Authentication
        Add Facebook Authentication
        Add Collection-Level Watch
Users & Authentication
MongoDB Atlas
GraphQL
MongoDB Mobile
Functions
Triggers
External Services
Values & Secrets
Application Deployment
Hosting
Troubleshooting
Stitch Administration
Application Logs
Client SDKs
Release Notes

Stitch > Tutorials > To-Do App Tutorial 

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:
…/…/…/_images/oauth.png

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.
1
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 the SHA1 fingerprint, run the following command in a terminal or Windows Command Prompt:

keytool -exportcert -alias androiddebugkey -keystore

Terminal example:

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v

Windows Command Prompt example:

keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore -list -v

Tip

If using debug.keystore, the password is android.

Enter the SHA1 fingerprint. For more information and an example, see Google Setting up OAuth 2.0 Help page

For Package name, enter the following:

com.mongodb.stitch.android.tutorials.todo

The package name may be found in the ToDo Android application project’s AndroidManifest.xml

Click 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:

https://stitch.mongodb.com

For Authorized redirect URIs, enter the following:

    https://stitch.mongodb.com/api/client/v2.0/auth/callback

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.

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

3
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.
1
Get the latest code

In the MongoDB Stitch Android tutorial repo, run the following command to fetch the tagged version for this tutorial:

git checkout google-oauth

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.
2
Add Google Libraries to Gradle

Open the project-level Gradle file.

Add the following lines to the dependencies:

implementation 'com.google.gms:google-services:4.0.1'
implementation 'com.google.firebase:firebase-core:16.0.1'
implementation 'com.google.android.gms:play-services-auth:16.0.0'

3
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:

<resources>
  <string name="app_name">Todo</string>
  <string name="login_action_label">Log in</string>
  <string name="add_item_action_label">Add</string>
  <string name="clear_checked_action_label">Clear Checked</string>
  <string name="clear_all_action_label">Clear All</string>
  <string name="edit_item_hint">Edit Item</string>
  <string name="stitch_client_app_id">todo_android_app-aabdc</string>
  <string name="google_web_client_id">153606348891-b0vmthckcud6dvlg60qi2rcilabcdef.apps.googleusercontent.com</string>
</resources>

4
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 a com.google.android.gms.common.SignInButton. The android:id property should be set to @+id/google_login_button. Your code may look like the following:

<com.google.android.gms.common.SignInButton
  android:id="@+id/google_login_button"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" />

5
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 new GoogleSignInOptions object by calling build() on a GoogleSignInOptions.Builder object. Your code should look like this:

// 1. Create a new GoogleSignInOptions object by calling build() on a
// new GoogleSignInOptions.Builder object.
final GoogleSignInOptions gso =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestServerAuthCode(googleWebClientId, true).build();

The GoogleSignInOptions object is used to create a GoogleApiClient, 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 new GoogleApiClient.Builder object. Your code should look like this:

// 2. Initialize the _googleApiClient
_googleApiClient = new GoogleApiClient.Builder(LogonActivity.this)
.enableAutoManage(LogonActivity.this, connectionResult ->
Log.e(“Stitch Auth”, "Error connecting to google: " + connectionResult.getErrorMessage()))
.addApi(GOOGLE_SIGN_IN_API, gso)
.build();

Now you need to attach an onClick hanlder for the button we added to the layout file above. Your code should look like this:

// 3. Create an onclick listener for the google_login_button
findViewById(R.id.google_login_button).setOnClickListener(v -> {
if (!_googleApiClient.isConnected()) {
_googleApiClient.connect();
}
GoogleSignInClient mGoogleSignInClient =
GoogleSignIn.getClient(LogonActivity.this, gso);

Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, GOOGLE_SIGN_IN);

});

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 the requestCode is GOOGLE_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 the onActivityResult), so we’ll pass the task to a separate method. Your code should look like this:

// 4. Handle the result that Google sends back to us
if (requestCode == GOOGLE_SIGN_IN) {
Task task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleGoogleSignInResult(task);
return;
}

Now we need to add functionality to the handleGoogleSignInResult() that we call above. We need to convert the returned task to a GoogleSignInAccount. The GoogleSignInAccount carries the Google server authentication code, which we will send to the Stitch backend:

// 5. Create a GoogleSignInAccount from the task result.
GoogleSignInAccount account = completedTask.getResult(ApiException.class);

// Create a GoogleCredential from the account.
final GoogleCredential googleCredential =
new GoogleCredential(account.getServerAuthCode());

Now that we’ve authenticated against Google, we need to authenticate with Stitch. We already have a static StitchAppClient defined in the TodoListActivity, so we’ll pass the GoogleCredential to the loginWithCredential method and handle the result of that call. Your code should look like this:

// 6. Authenticate against Stitch. If the task is successful, set the result to
//    Activity.RESULT_OK and end this activity, returning control to the TodoListActivity
TodoListActivity.client.getAuth().loginWithCredential(googleCredential).addOnCompleteListener(
  task -> {
    if (task.isSuccessful()) {
        setResult(Activity.RESULT_OK);
        finish();
    } else {
        Log.e("Stitch Auth", "Error logging in with Google", task.getException());
    }
});

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:
../../../_images/android-todo-google-login1.png

Clicking the button brings up the Google authentication options:
../../../_images/android-todo-google-login2.png

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.
← Build the To-Do Client Add Facebook OAuth to the To-Do Client →

© MongoDB, Inc 2008-present. MongoDB, Mongo, and the leaf logo are registered trademarks of MongoDB, Inc.
Was this page helpful?
Yes
No

 类似资料:

相关阅读

相关文章

相关问答