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 Google Chat REST 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:

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. Open the Google Cloud Console.
  2. At the top-left, click Menu > APIs & Services > OAuth consent screen.
  3. Select the user type for your app, then click Create.
  4. Complete the app registration form, then click Save and Continue.
  5. Click Add or Remove Scopes. Add and verify the authorization scopes required by your app, click Update, then click Save and Continue.

  6. 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. Open the Google Cloud console.
  2. At the top-left, click Menu > APIs & Services > Credentials.
  3. Click Create Credentials > OAuth client ID.
  4. Click Application type > Web application.
  5. In the "Name" field, type a name for the credential. This name is only shown in the Google Cloud console.
  6. 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, .NET, and more) – Under "Authorized redirect URIs," click Add URI. Then, enter an endpoint URI to which the OAuth 2.0 server can send responses.
  7. Click Create. The OAuth client created screen appears, showing your new Client ID and Client secret.
  8. Note the Client ID. Client secrets aren't used for Web applications.
  9. Click OK. The newly created credential appears under "OAuth 2.0 Client IDs."
  10. Optional: If you're creating credentials as a prerequisite for a JavaScript quickstart, you must also generate an API key.

Android

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

iOS

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

Chrome app

  1. Open the Google Cloud console.
  2. At the top-left, click Menu > APIs & Services > Credentials.
  3. Click Create Credentials > OAuth client ID.
  4. Click Application type > Chrome app.
  5. In the "Name" field, type a name for the credential. This name is only shown in the Google Cloud console.
  6. 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.
  7. Click Create. The OAuth client created screen appears, showing your new Client ID and Client secret.
  8. Click OK. The newly created credential appears under "OAuth 2.0 Client IDs."

Desktop app

  1. In the Google Cloud console, go to the Credentials page.

    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. Open the Google Cloud console.
  2. At the top-left, click Menu > APIs & Services > Credentials.
  3. Click Create Credentials > OAuth client ID.
  4. Click Application type > TVs & Limited Input devices.
  5. In the "Name" field, type a name for the credential. This name is only shown in the Google Cloud console.
  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."

Universal Windows Platform (UWP)

  1. Open the Google Cloud console.
  2. At the top-left, click Menu > APIs & Services > Credentials.
  3. Click Create Credentials > OAuth client ID.
  4. Click Application type > Universal Windows Platform (UWP).
  5. In the "Name" field, type a name for the credential. This name is only shown in the Google Cloud console.
  6. 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.
  7. Click Create. The OAuth client created screen appears, showing your new Client ID and Client secret.
  8. 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. Open the Google Cloud Console.
  2. At the top-left, click Menu > APIs & Services > Credentials.
  3. Under OAuth 2.0 Client IDs, click the client ID you made.
  4. Click Download JSON.
  5. 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 REST API. It authenticates with the Chat REST 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.
    service = build('chat', 'v1', 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 REST 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.