Authenticate and authorize users (Developer Preview)

Stay organized with collections Save and categorize content based on your preferences.

This guide explains how to use OAuth 2.0 with users' Google credentials to access the Chat API. First, it walks you through how to create OAuth 2.0 Client ID credentials. Then, it demonstrates how to write a script that uses the credentials to authenticate with the Chat API and add the Chat app to a Chat space.

Authenticating and authorizing with user credentials lets Chat apps access user data and perform operations on the authenticated user's behalf. For example, after authenticating and authorizing user credentials, Chat apps can:

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

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

If your Chat app doesn't access user data or perform actions on a user's behalf, consider authenticating as an app instead.

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.

Prerequisites

To run the example in this guide, you need the following prerequisites:

Python

Step 1: Install the Google client library

If you have not 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.

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 below 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.
  8. Optional: If you're creating credentials as a prerequisite for a JavaScript quickstart, you must also generate an API key.

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 you made.

  3. Click Download JSON.

  4. Save the file as client_secrets.json.

Step 4: Create an API key

While user authentication for Chat API is in developer preview, your code must point to a developer preview version of the Chat API discovery document. To authenticate the Google Cloud project's access to the developer preview version of the API, generate an API key in the project and pass it as part of the API call.

To create an API key:

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

    Go to Credentials

  2. Click Create credentials > API key.
  3. Your new API key is displayed.
    • Click Copy to copy your API key for use in your app's code. The API key can also be found in the "API keys" section of your project's credentials.
    • Click Restrict key to update advanced settings and limit use of your API key. For more details, see Applying API key restrictions.

Step 5: 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, then adds the Chat app to a space.

Save the following code in a file named chat_create_membership.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.memberships.app"]

def main():
    '''
    Authenticates with Chat API via user credentials,
    then adds the Chat app to a Chat space.
    '''

    # Start with no credentials.
    creds = None

    # Check for the file token.json. If it exists, use it for authentication.
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)

    # If there are no valid credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'client_secrets.json', SCOPES)
            creds = flow.run_local_server(port=0)

        # Save the credentials for the next run in a file
        # named token.json.
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    # Build a service endpoint for Chat API.
    #
    # While user authentication is in developer preview, append the
    # following parameters that let the Python client see a
    # developer preview version of the client library:
    #
    # discoveryServiceUrl—Points to a developer preview version of the Chat
    # API discovery document.
    #
    # developerKey—An API key created inside the developer preview Google
    # Cloud Project. This API key is used to authenticate the Cloud Project's
    # access to a developer preview API.
    key = 'API_KEY'
    url = 'https://chat.googleapis.com/$discovery/rest?version=v1&labels=DEVELOPER_PREVIEW'
    service = build('chat', 'v1', discoveryServiceUrl=url, developerKey=key, credentials=creds)

    # Set the Chat app as the entity that gets added to the space.
    # 'app' is an alias for the Chat app running the script.
    #
    # To specify a user, set:
    #
    # member = {
    #   'member': {
    #     'name':'users/{user}',
    #     'type':'HUMAN'
    #   }
    # }
    member = {
      'member': {
        'name':'users/app',
        'type': 'BOT'
      }
    }

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

      # Replace SPACE with a space name.
      # Obtain the space name from the spaces resource of Chat API,
      # or from a space's URL.
      parent='spaces/SPACE',
        body=member).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_create_membership.py and client_secrets.json, then execute the following command:

Python

python3 chat_create_membership.py

A web browser opens and prompts you to log in to your Google account:

Signing in to authorize a Chat app

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

Granting permission via the OAuth consent screen to a Chat 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

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

When running chat_create_membership.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 you downloaded from Google Cloud Platform 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 Google Cloud console again, and save the new file in the current file's place.

Next step

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