Navigation

Google Authentication

Google authentication allows users to log into a MongoDB Stitch application with an existing Google acount. This is accomplished by adding Google Sign-In to your client application, and configuring it to work with MongoDB Stitch’s authentication framework.

Create OAuth Client ID Credentials

Follow the directions at Google’s support website to create OAuth client ID credentials for your application.

When configuring the OAuth client ID credentials, use the following settings, even if you are building a mobile client application:

  • 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
    

If you are building a mobile client application, follow the additional steps below for your specific platform:

Additional Steps For Android Applications

Create an additional OAuth client ID with the following configuration:

  • 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 <path to debug.keystore> -list -v
    

    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

  • Enter the package name for your project. The package name can be found in your Android application project’s AndroidManifest.xml file.

  • Add the Google Sign-In button to your app. The instructions beginning here cover the basics.

    • When configuring the GoogleSignInOptions, ensure that you build it with a call to requestServerAuthCode. For the serverClientId parameter to this function, use the client ID for web applications that you configured in the previous section.

      GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
          .requestEmail()
          .requestServerAuthCode("<web-application-client-id>")
          .build();
      
      yourGoogleSignInClient = GoogleSignIn.getClient(yourSignInActivity, gso);
      

      If you don’t want to hard-code the web application client ID in your app, you can use the getAuthProviders method on the StitchClient class to fetch the client ID from MongoDB Stitch:

      yourStitchClient.getAuthProviders().addOnCompleteListener(new OnCompleteListener<AvailableAuthProviders>() {
           @Override
           public void onComplete(@NonNull Task<AvailableAuthProviders> task) {
               if (task.isSuccessful()) {
                   AvailableAuthProviders authInfo = task.getResult();
                   String serverClientId = authInfo.getGoogle().getConfig().getClientId();
      
                   GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                           .requestEmail()
                           .requestServerAuthCode(serverClientId)
                           .build();
      
                   yourGoogleSignInClient = GoogleSignIn.getClient(yourSignInActivity, gso);
      
               } else {
                   Log.e("stitch", "failed to get auth provider information to configure google auth provider");
               }
           }
       });
      
  • Once completed, make note of where a successful login is handled, as this will be where you authenticate with MongoDB Stitch using the Google authentication provider.

Additional Steps for iOS Applications

  1. Go to https://developers.google.com/mobile/add

  2. Select iOS App when picking a platform.

  3. Select the Google project you used when creating the web application OAuth Client ID.

  4. Enter your Bundle ID. In XCode, the bundle ID can be found in the General tab for the primary target of your iOS application.

  5. Select Choose and configure services.

  6. Select Google Sign-In and click Enable Google Sign-In.

  7. Click Generate configuration files.

  8. Download the GoogleService-Info.plist.

  9. Drag the GoogleService-Info.plist file into your XCode project, and be sure to add it to all of your project’s targets.

  10. Add the Google Sign-In SDK to your project by following the instructions on the page. CocoaPods must be installed and configured for your project.

  11. Follow the instructions at this page to enable and integrate the Google Sign-In SDK in your application.

  12. Wherever you configure the Google sign-in service (for example, in the application:didFinishLaunchingWithOptions: method in your app delegate), add the following line of code:

    GIDSignIn.sharedInstance().serverClientID = "<web-application-client-id>"
    

    Ensure that the client ID you use here is the client ID you configured for web applications, not the one for iOS applications. Otherwise you will receive the error message “error exchanging access code with OAuth2 provider” from MongoDB Stitch.

    If you don’t want to hard-code the web application client ID in your app, you can use the fetchAuthProviders method on the StitchClient class:

    yourStitchClient.fetchAuthProviders()
        .done { (authProviderInfo: AuthProviderInfo) in
            GIDSignIn.sharedInstance().serverClientID = authProviderInfo.googleProviderInfo?.config.clientId
        }.catch { error in
            print("Error fetching auth providers from Stitch")
    }
    
  13. Once completed, make note of where a successful login is handled, as this will be where you authenticate with MongoDB Stitch using the Google authentication provider.

Enable and Configure Google Authentication in MongoDB Stitch

Once you have the Client ID and Client Secret, use the following procedure in the MongoDB Stitch admin console to enable and configure the Google authentication provider:

  1. Click Authentication. The page displays the Authentication Providers.

  2. For Google, click the Edit button.

  3. In the Edit Provider dialog,

    1. Switch Google to enabled.

    2. Enter values for the following fields as appropriate:

      Field Description
      Client ID Required. The OAuth 2.0 client ID for the web application credentials you created in the Google Cloud Console.
      Client Secret Required. The OAuth 2.0 client secret for the web application credentials you created in the Google Cloud Console.
      Redirect URIs

      Required for web applications. These are the URIs that MongoDB Stitch is allowed to redirect the end user to after completing the authentication step. If a redirect URL is specified in the authentication process and it’s not an exact match with one of the URIs specified in this configuration setting, there will be an error.

      For example, if MongoDB Stitch needs to redirect to http://myapp.example.com/ after authentication, you must specify the URI exactly in this list, including the http and the trailing slash.

      Domain Restrictions

      Optional. If specified, accounts can only be created in MongoDB Stitch through this authentication provider when the email address of the Google account has one of the domains specified here.

      For example, if mycompany.com and mycompany.org are specified here, Google accounts where the email address is jane@mycompany.com or john@mycompany.org would be permitted, whereas emails like bob@gmail.com would be restricted.

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

      Metadata Fields

      Optional. The fields selected here will determine which fields from the user’s Google account are exposed in the data field of the user in MongoDB Stitch.

      If you’ve specified any domain restrictions, you must at a minimum expose the email address field.

    3. Click Save.

Incorporate into a Client Application

In web applications, the Google authentication provider works by redirecting the user to a Google webpage that handles authentication, and then redirecting the user back to your application with a MongoDB Stitch session at a URL of your choice.

In the JavaScript SDK, you can call the authenticate() method on the StitchClient with the "google" argument to trigger this authentication flow.

import { StitchClientFactory } from 'mongodb-stitch';
const stitchClientPromise = StitchClientFactory.create('<your-app-id>');

stitchClientPromise.then(stitchClient => {
   stitchClient.authenticate("google");
});

No redirect URL is specified here, so by default, the end user will be redirected back to the current root URL after they complete the Google sign-in. The current root URL is the current URL, minus any fragment identifiers.

For example, if the current page is http://myexample.com/dashboard/#login, the default redirect URI will be http://myexample.com/dashboard/.

If you would like to specify a specific URL to redirect to, you can call the authenticate method on the StitchClient with an additional options argument that specifies the redirectUrl.

stitchClientPromise.then(stitchClient => {
   stitchClient.authenticate("google", { redirectUrl: "<your-redirect-url>" });
});

If the redirect URL (default or otherwise) is not in the list of valid redirect URIs specified when you set up the Google authentication provider, the login flow will not successfully complete.

In mobile applications, this redirect step is not necessary. The Google Sign-In is handled by the Google Sign-In SDK for your specific platform, and you provide it with a callback that will call the authentication method in your platform-specific MongoDB Stitch SDK.

Wherever the Google Sign-In SDK handles a successful login for your app, you must call the StitchClient’s login method with the Google authentication provider. The provider object will need to be initialized with an authentication code you can get from the Google Sign-In SDK. Additionally, you should log out your user from MongoDB Stitch when they log out of Google.

Tip

In Android, you can get the authentication code by calling getServerAuthCode() on the GoogleSignInAccount object returned on a successful sign-in.

In iOS, you can get the authentication code by accessing the serverAuthCode property on the GIDGoogleUser object returned on a successful sign-in.

Tip

If you are having trouble getting the SDK to authenticate with MongoDB Stitch using the Google authentication provider, ensure that when logging in with the Google Sign-In SDK, you are requesting permission to access all the metadata that you’ve configured Stitch to request in the admin console.

See this page in the Google Sign-In Android documentation, or this page in the Google Sign-In iOS documentation for details on how to do this. A list of available scopes to request can be found here.

For detailed examples of how to incorporate Google authentication in a client application, each of the ToDo sample apps contain code for authenticating with Google.