Authenticate and authorize users

This guide explains how to use OAuth 2.0 with users' Google credentials to access the Chat API. Authenticating and authorizing with user credentials lets Chat apps access user data and perform operations on the authenticated user's behalf. By authenticating on a user's behalf, the app has the same permissions as that user and can perform actions as if it were performed by that user. However, these Chat apps can't be published publicly. For more information, see Publish Google Chat apps.

After authenticating and authorizing an API call with user credentials, Chat apps can do the following:

  • Create Chat spaces.
  • Add users to Chat spaces and group conversations.
  • Work with user data in other Workspace APIs such as the following:

When an app performs an action with user authentication (such as creating a space), Google Chat displays an attribution message that tells users the name of the app that performed the action for the user who authorized it.

To learn more about when Chat apps require authentication and what kind of authentication to use, see Types of required authentication in the Chat API authentication and authorization overview.

If you're a domain administrator, you can grant domain-wide delegation of authority to authorize an application's service account to access your users' data without requiring each user to give consent. After you configure domain-wide delegation, the service account can impersonate a user account. Although a service account is used for authentication, domain-wide delegation impersonates a user and is therefore considered user authentication. Any functionality that requires user authentication, you can use domain-wide delegation.

To use the Google Chat API to access or modify resources of a Google Workspace organization, the user must be a member of that organization. External users or users without a Google Workspace account with access to Google Chat aren't supported.

Prerequisites

Python

Step 1: Install the Google client library

If you haven't already installed the Google client libraries for your language of choice, run the following command in your command-line interface:

Python

pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib oauth2client

You can use any language supported by our client libraries.

Step 2: Configure the OAuth consent screen, specify scopes, and register your app

When you use OAuth 2.0 for authorization, Google displays a consent screen to the user including a summary of your project, its policies, and the requested authorization scopes. Configuring your app's OAuth consent screen defines what Google displays to users and app reviewers, and registers your app so you can publish it later.

All apps using OAuth 2.0 require a consent screen configuration, but you only need to list scopes for apps used by people outside your Google Workspace organization.

  1. In the Google Cloud console, go to Menu > APIs & Services > OAuth consent screen.

    Go to OAuth consent screen

  2. Select the user type for your app, then click Create.

  3. Complete the app registration form, then click Save and Continue.

  4. Click Add or Remove Scopes. Add and verify the authorization scopes required by your app, click Update, then click Save and Continue.

  5. Review your app registration summary. Click Edit to make changes, or click Back to Dashboard.

Step 3: Create OAuth client ID credentials in Google Cloud console

To authenticate as an end user and access user data in your app, you need to create one or more OAuth 2.0 Client IDs. A client ID is used to identify a single app to Google's OAuth servers. If your app runs on multiple platforms—like Android, iOS, and Web—you need to create a separate client ID for each platform.

Create OAuth client ID credentials

Choose your application type for specific instructions about how to create an OAuth client ID:

Web application

  1. In the Google Cloud console, go to Menu > APIs & Services > Credentials.

    Go to Credentials

  2. Click Create Credentials > OAuth client ID.
  3. Click Application type > Web application.
  4. In the Name field, type a name for the credential. This name is only shown in the Google Cloud console.
  5. Add authorized URIs related to your app:
    • Client-side apps (JavaScript)–Under Authorized JavaScript origins, click Add URI. Then, enter a URI to use for browser requests. This identifies the domains from which your application can send API requests to the OAuth 2.0 server.
    • Server-side apps (Java, Python, and more)–Under Authorized redirect URIs, click Add URI. Then, enter an endpoint URI to which the OAuth 2.0 server can send responses.
  6. Click Create. The OAuth client created screen appears, showing your new Client ID and Client secret.

    Note the Client ID. Client secrets aren't used for Web applications.

  7. Click OK. The newly created credential appears under OAuth 2.0 Client IDs.

Android

  1. In the Google Cloud console, go to Menu > APIs & Services > Credentials.

    Go to Credentials

  2. Click Create Credentials > OAuth client ID.
  3. Click Application type > Android.
  4. In the "Name" field, type a name for the credential. This name is only shown in the Google Cloud console.
  5. In the "Package name" field, enter the package name from your AndroidManifest.xml file.
  6. In the "SHA-1 certificate fingerprint" field, enter your generated SHA-1 certificate fingerprint.
  7. Click Create. The OAuth client created screen appears, showing your new Client ID.
  8. Click OK. The newly created credential appears under "OAuth 2.0 Client IDs."

iOS

  1. In the Google Cloud console, go to Menu > APIs & Services > Credentials.

    Go to Credentials

  2. Click Create Credentials > OAuth client ID.
  3. Click Application type > iOS.
  4. In the "Name" field, type a name for the credential. This name is only shown in the Google Cloud console.
  5. In the "Bundle ID" field, enter the bundle identifier as listed in the app's Info.plist file.
  6. Optional: If your app appears in the Apple App Store, enter the App Store ID.
  7. Optional: In the "Team ID" field, enter the unique 10-character string, generated by Apple and assigned to your team.
  8. Click Create. The OAuth client created screen appears, showing your new Client ID and Client secret.
  9. Click OK. The newly created credential appears under "OAuth 2.0 Client IDs."

Chrome app

  1. In the Google Cloud console, go to Menu > APIs & Services > Credentials.

    Go to Credentials

  2. Click Create Credentials > OAuth client ID.
  3. Click Application type > Chrome app.
  4. In the "Name" field, type a name for the credential. This name is only shown in the Google Cloud console.
  5. In the "Application ID" field, enter your app's unique 32-character ID string. You can find this ID value in your app's Chrome Web Store URL and in the Chrome Web Store Developer Dashboard.
  6. Click Create. The OAuth client created screen appears, showing your new Client ID and Client secret.
  7. Click OK. The newly created credential appears under "OAuth 2.0 Client IDs."

Desktop app

  1. In the Google Cloud console, go to Menu > APIs & Services > Credentials.

    Go to Credentials

  2. Click Create Credentials > OAuth client ID.
  3. Click Application type > Desktop app.
  4. In the Name field, type a name for the credential. This name is only shown in the Google Cloud console.
  5. Click Create. The OAuth client created screen appears, showing your new Client ID and Client secret.
  6. Click OK. The newly created credential appears under OAuth 2.0 Client IDs.

TVs & Limited Input devices

  1. In the Google Cloud console, go to Menu > APIs & Services > Credentials.

    Go to Credentials

  2. Click Create Credentials > OAuth client ID.
  3. Click Application type > TVs & Limited Input devices.
  4. In the "Name" field, type a name for the credential. This name is only shown in the Google Cloud console.
  5. Click Create. The OAuth client created screen appears, showing your new Client ID and Client secret.
  6. Click OK. The newly created credential appears under "OAuth 2.0 Client IDs."

Universal Windows Platform (UWP)

  1. In the Google Cloud console, go to Menu > APIs & Services > Credentials.

    Go to Credentials

  2. Click Create Credentials > OAuth client ID.
  3. Click Application type > Universal Windows Platform (UWP).
  4. In the "Name" field, type a name for the credential. This name is only shown in the Google Cloud console.
  5. In the "Store ID" field, enter your app's unique, 12-character Microsoft Store ID value. You can find this ID in your app's Microsoft Store URL and in the Partner Center.
  6. Click Create. The OAuth client created screen appears, showing your new Client ID and Client secret.
  7. Click OK. The newly created credential appears under "OAuth 2.0 Client IDs."

Download the client secret JSON file

The client secret file is a JSON representation of the OAuth client ID credentials that your Chat app can reference when providing credentials.

  1. In the Google Cloud console, go to Menu > APIs & Services > Credentials.

    Go to Credentials

  2. Under OAuth 2.0 Client IDs, click the client ID that you created.

  3. Click Download JSON.

  4. Save the file as client_secrets.json.

Step 4: Write a script that calls the Chat API

The following code uses a client library to call the Chat API. It authenticates with the Chat API using OAuth client ID credentials, and then creates a space.

Save the following code in a file named chat_space_create_named.py in the same directory that holds client_secrets.json:

Python

from __future__ import print_function

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# Define your app's authorization scopes.
# When modifying these scopes, delete the file token.json, if it exists.
SCOPES = ["https://www.googleapis.com/auth/chat.spaces.create"]

def main():
    '''
    Authenticates with Chat API via user credentials,
    then creates a Chat space.
    '''

    flow = InstalledAppFlow.from_client_secrets_file(
                      'client_secrets.json', SCOPES)
    creds = flow.run_local_server()

    # Build a service endpoint for Chat API.
    service = build('chat', 'v1', credentials=creds)

    # Use the service endpoint to call Chat API.
    result = service.spaces().create(

      # Details about the space to create.
      body = {

        # To create a named space, set spaceType to SPACE.
        'spaceType': 'SPACE',

        # The user-visible name of the space.
        'displayName': 'API-made'
      }

      ).execute()

    # Prints details about the created membership.
    print(result)

if __name__ == '__main__':
    main()

Step 5: Run the example script

To run the example, from the command line, navigate to the directory that holds chat_space_create_named.py and client_secrets.json, then execute the following command:

Python

python3 chat_space_create_named.py

A browser opens and prompts you to sign in to your Google Account:

Signing in to authorize a Chat app.

Figure 1. OAuth consent screen where you select which account to authenticate the app.

After you sign in, the OAuth consent screen appears and asks you to grant permission to the app.

After you grant permission, the script calls the Chat API, which responds by adding the Chat app to a Chat space. The console prints details of the API call.

Troubleshoot the example

When running chat_space_create_named.py, you might receive an error that says:

Expected a JSON object with a single property for a "web" or "installed" application

This error message means that the client_secrets.json file that you downloaded from the Google Cloud console doesn't begin with the "web" or "installed" property. After authenticating with the downloaded file, if your code doesn't save the access token in a new file like token.json, then the access token is written to client_secrets.json, which can cause this error during subsequent authorization attempts.

To resolve the error, download the client secret file from the Google Cloud console again, and save the new file in the current file's place.

Learn what else Chat API can do by reviewing the Chat API reference documentation.