Authenticate as a Chat app

This guide explains how to set up and use a service account to access the Google Chat REST API on behalf of a Chat app. First, it walks you through how to create a service account. Then, it demonstrates how to write a script that uses the service account to authenticate with the Chat API and post a message in a Chat space.

Chat apps can use service accounts to authenticate when asynchronously calling the Google Chat REST API so they can:

  • Send messages to Google Chat with spaces.messages.create to:
    • Notify users when a long-running background job finishes running.
    • Alert users that a server has gone offline.
    • Ask a customer support person to tend to a newly opened customer case.
  • Update previously sent messages with spaces.messages.update to:
    • Change the status of on ongoing operation.
    • Update a task's assignee or due date.
  • List users in a space with spaces.members.list to:
    • See who is in a space.
    • Verify space membership includes everyone on a team.

When authenticated with a service account, to get data about or perform actions in a Chat space, Chat apps must have membership in the space. For example, to list members of a space, or to create a message in a space, the Chat app has to itself be a member of the space.

If your Chat app needs to access user data or perform actions on a user's behalf, authenticate as a user instead.

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, you can make API calls using your service account to 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 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: Create a service account in Google Cloud Console

Create a service account that your Chat app will use to access Google APIs.

Create a service account:

To create a service account, follow these steps:

  1. In the Google Cloud console, go to Menu > IAM & Admin > Service Accounts.

    Go to Service Accounts

  2. Click Create service account.
  3. Fill in the service account details, then click Create and continue.
  4. Optional: Assign roles to your service account to grant access to your Google Cloud project's resources. For more details, refer to Granting, changing, and revoking access to resources.
  5. Click Continue.
  6. Optional: Enter users or groups that can manage and perform actions with this service account. For more details, refer to Managing service account impersonation.
  7. Click Done. Make a note of the email address for the service account.

The service account appears on the service account page. Next, create a private key for the service account.

Create a private key

To create a private key for the service account, follow these steps:

  1. In the Google Cloud console, go to Menu > IAM & Admin > Service Accounts.

    Go to Service Accounts

  2. Select your service account.
  3. Click Keys > Add key > Create new key.
  4. Select JSON, then click Create.

    Your new public/private key pair is generated and downloaded to your machine as a new file. This file is the only copy of this key. For information about how to store your key securely, see Managing service account keys.

  5. Click Close.

For more information about service accounts, see service accounts in the Google Cloud IAM documentation.

Step 2: Write a script that uses the service account to authenticate with Chat REST API

The following code authenticates with the Chat REST API using a service account, then posts a message to a Chat space:

Python

  1. In your working directory, create a file named chat_app_auth.py.
  2. Include the following code in chat_app_auth.py:

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'service_account.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE_NAME with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE_NAME',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    print(result)
    
  3. In the code, replace SPACE_NAME with a space name, which you can obtain from the spaces.list method in Chat API, or from a space's URL.

Step 3: Run the complete example

In your working directory, build and run the sample:

Python

python3 chat_app_auth.py

Your script makes an authenticated request to the Chat REST API, which responds by posting a message in a Chat space as a Chat app.

Troubleshoot the example

This section describes common issues that you might encounter while attempting to run this sample.

You are not permitted to use this app

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

<HttpError 403 when requesting https://chat.googleapis.com/v1/spaces/{space}/messages?alt=json returned "You are not permitted to use this app". Details: "You are not permitted to use this app">

This error message means that the Chat app doesn't have permission to post Chat messages in the Chat space it's trying to post to.

To resolve the error, add the Chat app to the Chat space specified in chat_app_auth.py.

Next step

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