Navigation

Google Authentication

Overview

The Google authentication provider allows users to log in with their existing Google account through Google Sign-In. When a user logs in, Google provides Stitch with an OAuth 2.0 access token for the user. Stitch uses the token to identify the user and access approved data from Google APIs on their behalf.

Configuration

You can enable and configure the Google authentication provider from the Stitch UI by selecting Google from the Users > Providers page.

You can enable and configure the Google authentication provider with stitch-cli by importing an application directory that contains a configuration file for the provider.

The configuration file must be named oauth2-google.json and stored in the /auth_providers directory. Configuration files for the Google authentication provider have the following form:

/auth_providers/oauth2-google.json
{
  "name": "oauth2-google",
  "type": "oauth2-google",
  "disabled": <boolean>,
  "config": {
    clientId: <string>
  },
  "metadata_fields": [<document>, ...],
  "redirect_uris": [<string>, ...],
  "domain_restrictions": [<string>, ...]
}

The Google authentication provider has the following configuration options:

Field Description

Client ID

config.clientId

Required. An OAuth 2.0 Client ID for your Google Cloud Platform project.

See Set Up a Google Cloud Platform Project for information about setting up OAuth Credentials for your GCP project.

Client Secret

Defined in secrets.json

Required. An OAuth 2.0 Client Secret for your Google Cloud Platform project.

See Set Up a Google Cloud Platform Project for information about setting up OAuth Credentials for your GCP project.

Note

Client Secret is not defined in the provider configuration file for import/export. Instead, it’s defined in secrets.json using the following form:

"auth_providers": {
  "oauth2-google": {
    "clientSecret": "<secret>"
  }
}

Metadata Fields

metadata_fields

Optional. A list of fields describing the authenticated user that your application will request from the Google Identity API.

All metadata fields are omitted by default and can be required on a field-by-field basis. Users must explicitly grant your app permission to access each required field. If a metadata field is required and exists for a particular user, it will be included in their user object.

To require a metadata field from an import/export configuration file, add an entry for the field to the metadata_fields array. Each entry should be a document of the following form:

{ name: "<metadata field name>", required: "<boolean>" }

Redirect URIs

redirect_uris

Required for web applications. A list of allowed redirect URIs.

Once a user completes the authentication process on Google, Stitch redirects them back to either a specified redirect URI or, if no redirect URI is specified, the URL that they initiated the authentication request from. Stitch will only redirect a user to a URI that exactly matches an entry in this list, including the protocol and any trailing slashes.

Domain Restrictions

domain_restrictions

Optional. A list of approved domains for user accounts.

If specified, the provider checks the domain of a user’s primary email address on Google and only allows them to authenticate if the domain matches an entry in this list.

For example, if example.com and example2.com are listed, a Google user with a primary email of joe.schmoe@example1.com would be allowed to log in, while a user with a primary email of joe.schmoe@example3.com would not be allowed to log in.

Note

If you’ve specified any domain restrictions, you must also require the email address field in the Metadata Fields setting.

Usage

Set Up a Google Cloud Platform Project

The Google authentication provider requires a Google Cloud Platform project to manage authentication and user permissions. The following steps walk through creating the project, generating OAuth credentials, and configuring the provider to connect with the project.

1

Create a Google Cloud Platform Project

Follow Google’s official guide to create a new GCP project.

2

Generate OAuth Client Credentials

Note

For iOS client applications, you need to create both a Web OAuth Client ID and an iOS OAuth Client ID. The former is used by Stitch, while the latter will be used by the app itself.

Refer to the Web tab of this section for instructions on creating the web application Client ID for Stitch.

Follow Google’s support guide on Setting up OAuth 2.0 for your project.

Use the following values when configuring your web application Client ID:

Application Type Web Application
Name The name you wish to associate with this Client ID
Authorized JavaScript Origins
https://stitch.mongodb.com
Authorized Redirect URIs
https://stitch.mongodb.com/api/client/v2.0/auth/callback

Use the following values when configuring your Android application Client ID:

Application Type Android
Name The name you wish to associate with this Client ID.
Signing-certificate Fingerprint The SHA-1 fingerprint of your application signing certificate. See Authenticating Your Client for instructions on generating this value.

Use the following values when configuring your iOS application Client ID:

Application Type iOS
Name The name you wish to associate with this Client ID.
Bundle ID The Bundle ID for your iOS application. You can find this value in XCode on the General tab for the app’s primary target.
3

Configure the Google Authentication Provider

To connect your GCP project to Stitch add the OAuth 2.0 Client ID and Client Secret you generated in the previous step to your authentication provider configuration.

Note

Make sure that you add the web application credentials to the provider configuration. If you add the iOS credentials instead, Google authentication will fail.

Authenticate a User

To begin authenticating a user with the Google authentication provider, call StitchAuth.loginWithRedirect() an instance of GoogleRedirectCredential:

const credential = new GoogleRedirectCredential()
Stitch.defaultAppClient.auth.loginWithRedirect(credential);

In web apps, Google authentication redirects users to a page hosted on a Google domain. Once a user enters their credentials on this page, Google will confirm or deny their identity and, if successfully authenticated, ask them for permission to share their data with the application. Google will then redirect to Stitch, where the user’s access token is saved and the user is redirected back to the redirect URI. The redirect URI must appear in the list of Redirect URIs specified in the provider configuration, otherwise the login process will not complete successfully.

By default, Stitch redirects users to the URL of the page from which they initiated the login request. To specify a redirect URI, include it as a parameter to the GoogleRedirectCredential constructor:

const credential = new GoogleRedirectCredential("<URL>")
Stitch.defaultAppClient.auth.loginWithRedirect(credential);

Note

The redirect URI is automatically stripped of any fragment identifiers.

For example, if the initial redirect URL is https://example.com/dashboard/#login, the user will be redirected to https://example.com/dashboard/.

Dependency

You must install the Google Sign-In SDK for Android to use the Google authentiction provider in an Android application.

In Android applications, Google authentication is handled by the GoogleSignInClient class. When a user clicks the login button, GoogleSignInClient creates a signInIntent and redirects users to a login form on a Google domain. Google confirms or denies their identity and ask them for permission to share their data with your application. When the user has finished the sign-in process, the Google SDK returns a GoogleSignInResult object in the sign-in intent.

If the sign-in process was succesful, the sign-in result resolves to a GoogleSignInAccount object. Access the user’s account object by passing the intent as an argument to getSignedInAccountFromIntent() and calling getResult() on the task it returns.

Finally, get a server authorization code from the account by running getServerAuthCode() on the account object. Instantiate a new GoogleCredential with the authorization code and pass the provider as an argument to StitchAuth.loginWithCredential().

For more detailed instructions on integrating Google Sign-In into your Android application, see the official Google guide.

Note

Ensure that you configure the Google Sign-In SDK to request access permissions for each metadata field configured in the authentication provider. See Requesting Additional Scopes for details on how to do this. A list of available scopes can be found here.

// Login Button onClick Handler
public void onClick(final View ignored) {
  Intent signInIntent = googleSignInClient.getSignInIntent();
  startActivityForResult(signInIntent, RC_SIGN_IN);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RC_SIGN_IN) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        handleGooglSignInResult(task);
        return;
    }
}

private void handleGooglSignInResult(Task<GoogleSignInAccount> completedTask) {
  try {
    GoogleSignInAccount account = completedTask.getResult(ApiException.class);
    final GoogleCredential googleCredential =
          new GoogleCredential(account.getServerAuthCode());

    Stitch.getDefaultAppClient().getAuth().loginWithCredential(googleCredential).addOnCompleteListener(
      new OnCompleteListener<StitchUser>() {
        @Override
        public void onComplete(@NonNull final Task<StitchUser> task) {
          if (task.isSuccessful()) {
            // Do something here if the user logged in succesfully.
          } else {
            Log.e(TAG, "Error logging in with Google", task.getException());
          }
        }
    });
  } catch (ApiException e) {
    Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
  }
}

Dependency

You must install the Google Sign-In SDK for iOS to use the Google authentiction provider in an iOS application.

In iOS applications, Google authentication is handled by the GIDSignIn class. When a user clicks the login button, GIDSignIn redirects the user to a login form on a Google domain. Google confirms or denies their identity and ask them for permission to share their data with your application. When the user has finished the sign-in process, the Google SDK returns a GIDGoogleUser object to the GIDSignInDelegate handler function in your app delegate.

In the Sign-in delegate, get a server authorization code for the user by accessing the serverAuthCode property of the GIDGoogleUser object. Instantiate a new GoogleCredential with the authorization code and pass it to the StitchAuth.login(withCredential:_:) method 8as the withCredential argument.

For detailed instructions on integrating Google Sign-In into your iOS application, see the official Google guide.

Note

Ensure that you configure the Facebook SDK to request access permissions for each metadata field configured in the authentication provider. See Ask for Permissions in the Facebook Login SDK documentation for details on how to do this. A list of available permissions can be found here.

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
  if let error = error {
    print("error received when logging in with Google: \(error.localizedDescription)")
  } else {
    let googleCredential = GoogleCredential.init(withAuthCode: user.serverAuthCode)
    Stitch.defaultAppClient!.auth.login(withCredential: googleCredential) { result in
      switch result {
      case .success:
        self.delegate?.authenticationViewControllerDidLogin()
      case .failure(let error):
          print("failed logging in Stitch with Google. error: \(error)")
          GIDSignIn.sharedInstance().signOut()
      }
    }
  }
}