以 Google Chat 應用程式的身分進行驗證

本指南說明如何設定服務帳戶,並代表 Chat 應用程式使用 Google Chat API。首先,本指南會逐步引導您建立服務帳戶。接著示範如何編寫使用服務帳戶向 Chat API 進行驗證的指令碼,並在 Chat 聊天室中張貼訊息。

即時通訊應用程式可在非同步呼叫 Google Chat API 時,使用服務帳戶進行驗證,以便:

  • 透過 spaces.messages.create 傳送訊息至 Google Chat,以便:
    • 長時間執行背景工作完成時,通知使用者。
    • 提醒使用者伺服器離線。
    • 詢問客服人員通常對於新的客戶案件。
  • 使用 spaces.messages.update 將先前傳送的訊息更新為:
    • 變更執行中作業的狀態。
    • 更新工作的指派對像或到期日。
  • 使用 spaces.members.list 列出聊天室中的使用者,即可執行以下操作:
    • 查看聊天室成員。
    • 驗證聊天室成員包含所有團隊成員。

使用服務帳戶進行驗證時,如要取得 Chat 聊天室中相關資料或執行動作的資料,即時通訊應用程式必須具備聊天室成員資格。舉例來說,如要列出聊天室成員,或在聊天室中建立訊息,Chat 應用程式必須是聊天室的成員。

如果您的 Chat 應用程式需要存取使用者資料或對使用者執行動作,請改為以使用者的身分進行驗證

如果您是網域管理員,可以授予全網域授權委派,授權應用程式服務帳戶存取使用者資料,而不需要每位使用者取得同意。設定全網域委派功能後,您可以使用服務帳戶進行 API 呼叫,以模擬使用者帳戶。雖然服務帳戶是用於驗證,但全網域委派會冒用使用者,因此會視為使用者驗證。任何需要使用者驗證的功能都可以使用全網域委派。

如要進一步瞭解 Chat 擴充應用程式何時需要進行驗證,以及使用何種驗證機制,請參閱 Chat API 驗證與授權總覽中的「必要驗證類型」。

先備知識

如要執行本指南中的範例,您必須具備下列先決條件:

此外,您還需要下列特定語言的必備條件:

Java

  • JDK 1.7 以上版本
  • Maven 套件管理工具
  • 初始化的 Maven 專案。如要初始化新專案,請在指令列介面中執行下列指令:

    mvn archetype:generate -DgroupId=com.google.chat.app.authsample -DartifactId=auth-sample-app -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false
    

Python

  • Python 3.6 以上版本
  • pip 套件管理工具

Node.js

  • Node.js
  • npm 套件管理工具
  • 初始化的 Node.js 專案。如要初始化新專案,請建立並切換至新資料夾,然後在指令列介面中執行下列指令:

    npm init
    

Apps Script

步驟 1:在 Google Cloud 控制台中建立服務帳戶

建立服務帳戶,讓 Chat 應用程式可用來存取 Google API。

建立服務帳戶

如要建立服務帳戶,請按照下列步驟操作:

Google Cloud 控制台

  1. 在 Google Cloud 控制台中,依序點選「選單」圖示 >「IAM 與管理」>>「服務帳戶」

    前往「Service Accounts」(服務帳戶)

  2. 點選「建立服務帳戶」
  3. 填寫服務帳戶詳細資料,然後按一下「建立並繼續」。 注意:根據預設,Google 會建立不重複的服務帳戶 ID。
  4. 選用:為服務帳戶指派角色,授予 Google Cloud 專案資源的存取權。詳情請參閱「授予、變更及撤銷資源的存取權」。
  5. 點選「繼續」
  6. 選用:輸入可以透過這個服務帳戶管理及執行動作的使用者或群組。詳情請參閱「管理服務帳戶模擬功能」。
  7. 按一下 [完成]。記下服務帳戶的電子郵件地址。

gcloud CLI

  1. 建立服務帳戶:
    gcloud iam service-accounts create SERVICE_ACCOUNT_NAME \
      --display-name="SERVICE_ACCOUNT_NAME"
  2. 選用:為服務帳戶指派角色,授予 Google Cloud 專案資源的存取權。詳情請參閱「授予、變更及撤銷資源的存取權」。

服務帳戶會顯示在「服務帳戶」頁面中。接下來,為服務帳戶建立私密金鑰

建立私密金鑰

如要建立並下載服務帳戶的私密金鑰,請按照下列步驟操作:

  1. 在 Google Cloud 控制台中,依序點選「選單」圖示 >「IAM 與管理」>>「服務帳戶」

    前往「Service Accounts」(服務帳戶)

  2. 選取服務帳戶。
  3. 依序按一下「金鑰」>「新增金鑰」>「建立新的金鑰」
  4. 選取「JSON」,然後按一下「建立」

    系統會產生新的公開/私密金鑰組,並以新檔案的形式下載到您的電腦。將下載的 JSON 檔案儲存為 credentials.json 在您的工作目錄中。這個檔案是這組金鑰的唯一副本。如要瞭解如何安全儲存金鑰,請參閱管理服務帳戶金鑰

  5. 點選「關閉」

如要進一步瞭解服務帳戶,請參閱 Google Cloud IAM 說明文件中的服務帳戶

步驟 2:安裝 Google 用戶端程式庫和其他依附元件

安裝 Google 用戶端程式庫和專案需要的其他依附元件。

Java

如要將 Google 用戶端程式庫和其他必要的依附元件新增至 Maven 專案,請編輯專案目錄中的 pom.xml 檔案,並新增下列依附元件:

<dependencies>
  <!-- ... existing dependencies ... -->
  <dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-chat</artifactId>
    <version>v1-rev20230905-2.0.0</version>
  </dependency>
  <dependency>
    <groupId>com.google.auth</groupId>
    <artifactId>google-auth-library-oauth2-http</artifactId>
    <version>1.19.0</version>
  </dependency>
  <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.10.1</version>
  </dependency>
</dependencies>

Python

如果您尚未安裝 Python 適用的 Google 用戶端程式庫,請在指令列介面中執行下列指令:

pip3 install --upgrade google-api-python-client google-auth

Node.js

如要將 Google 用戶端程式庫新增到 Node.js 專案,請切換至專案目錄,然後在指令列介面中執行下列指令:

npm install "@googleapis/chat"

Apps Script

這個範例使用 Apps Script 的 OAuth2 程式庫產生服務帳戶驗證所需的 JWT 憑證。如要將程式庫加入 Apps Script 專案,請按照下列指示操作:

  1. 按一下左側的「編輯器」圖示
  2. 在左側的「程式庫」旁邊,按一下「新增程式庫」
  3. 輸入指令碼 ID 1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF
  4. 依序按一下「查詢」和「新增」

這個範例使用進階 Chat 服務來呼叫 Google Chat API。如要為 Apps Script 專案開啟服務,請按照下列步驟操作:

  1. 按一下左側的「編輯器」圖示
  2. 在左側的「Service」(服務) 旁邊,按一下「Add a service」(新增服務)
  3. 選取「Google Chat API」
  4. 在「版本」中選取「v1」
  5. 按一下「新增」。

您可以使用用戶端程式庫支援的任何語言。

步驟 3:編寫使用服務帳戶驗證 Chat API 的指令碼

下列程式碼會使用服務帳戶使用 Chat API 進行驗證,然後將訊息張貼至 Chat 聊天室:

Java

  1. 在專案的目錄中開啟 src/main/java/com/google/chat/app/authsample/App.java 檔案。
  2. App.java 中的內容替換為下列程式碼:

    package com.google.chat.app.authsample;
    
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.http.HttpRequestInitializer;
    import com.google.api.client.json.gson.GsonFactory;
    import com.google.api.services.chat.v1.HangoutsChat;
    import com.google.api.services.chat.v1.model.Message;
    import com.google.auth.http.HttpCredentialsAdapter;
    import com.google.auth.oauth2.GoogleCredentials;
    
    /**
     * Authenticates with Chat API via service account credentials,
     * then creates a Chat message.
     */
    public class App {
        // Specify required scopes.
        private static final String CHAT_SCOPE = "https://www.googleapis.com/auth/chat.bot";
    
        // Specify service account details.
        private static final String PRIVATE_KEY_RESOURCE_URI = "/credentials.json";
    
        public static void main( String[] args ) {
            try {
                // Run app.
                Message response = App.createChatMessage();
                // Print details about the created message.
                System.out.println(response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        private static Message createChatMessage() throws Exception {
            // Build the Chat API client and authenticate with the service account.
            GoogleCredentials credentials = GoogleCredentials.fromStream(
                App.class.getResourceAsStream(PRIVATE_KEY_RESOURCE_URI))
                .createScoped(CHAT_SCOPE);
            HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
            HangoutsChat chatService = new HangoutsChat.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                GsonFactory.getDefaultInstance(),
                requestInitializer)
                .setApplicationName("auth-sample-app")
                .build();
    
            // 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.
            String spaceName = "spaces/SPACE_NAME";
    
            // Create a Chat message.
            Message message = new Message().setText("Hello, world!");
            return chatService.spaces().messages().create(spaceName, message).execute();
        }
    }
    
  3. 在程式碼中,將 SPACE_NAME 替換為聊天室名稱,您可以從 Chat API 的 spaces.list 方法或聊天室網址取得。

  4. 在專案的目錄中建立名為 resources 的新子目錄。

  5. 確認服務帳戶的私密金鑰檔案名為 credentials.json,並將其複製到 resources 子目錄。

  6. 若要設定 Maven 以在專案套件中加入私密金鑰檔案,請編輯專案目錄中的 pom.xml 檔案,並將下列設定新增至 <build> 區段:

    <build>
      <!-- ... existing configurations ... -->
      <resources>
        <resource>
          <directory>resources</directory>
        </resource>
      </resources>
    </build>
    
  7. 如要設定 Maven 以在專案套件中加入依附元件,並執行應用程式的主要類別,請編輯專案目錄中的 pom.xml 檔案,並將下列設定新增至 <plugins> 區段:

    <plugins>
      <!-- ... existing configurations ... -->
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.google.chat.app.authsample.App</mainClass>
            </manifest>
          </archive>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
      </plugin>
    </plugins>
    

Python

  1. 在工作目錄中,建立名為 chat_app_auth.py 的檔案。
  2. chat_app_auth.py 中加入下列程式碼:

    from apiclient.discovery import build
    from google.oauth2 import service_account
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # 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()
    
    # Prints details about the created message.
    print(result)
    
  3. 在程式碼中,將 SPACE_NAME 替換為聊天室名稱,您可以從 Chat API 的 spaces.list 方法或聊天室網址取得。確認服務帳戶的私密金鑰檔案名為 credentials.json

Node.js

  1. 在專案的目錄中,建立名為 chat_app_auth.js 的檔案。
  2. chat_app_auth.js 中加入下列程式碼:

    const chat = require('@googleapis/chat');
    
    async function createMessage() {
      const auth = new chat.auth.GoogleAuth({
    
        // Specify service account details.
        keyFilename: 'credentials.json',
    
        // Specify required scopes.
        scopes: ['https://www.googleapis.com/auth/chat.bot']
    
      });
      const authClient = await auth.getClient();
    
      // Create the Chat API client and authenticate with the service account.
      const chatClient = await chat.chat({
        version: 'v1',
        auth: authClient
      });
    
      // Create a Chat message.
      const result = await chatClient.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.
        requestBody: { 'text': 'Hello, world!' }
    
      });
      return result;
    }
    
    // Execute function then print details about the created message.
    createMessage().then(console.log);
    
  3. 在程式碼中,將 SPACE_NAME 替換為聊天室名稱,您可以從 Chat API 的 spaces.list 方法或聊天室網址取得。確認服務帳戶的私密金鑰檔案名為 credentials.json

Apps Script

  1. 在 Apps Script 編輯器中,編輯 appsscript.json 檔案並新增發出外部要求所需的 OAuth 範圍,以取得服務帳戶 OAuth 權杖:

      "oauthScopes": [
        "https://www.googleapis.com/auth/script.external_request"
      ]
    
  2. 將下列程式碼儲存在 Apps Script 專案中名為 ChatAppAuth.gs 的檔案:

    // Specify the contents of the file credentials.json.
    const CREDENTIALS = CREDENTIALS;
    
    const SCOPE = 'https://www.googleapis.com/auth/chat.bot';
    
    // 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.
    const PARENT = 'spaces/SPACE_NAME'
    
    /**
     * Authenticates with Chat API via app credentials, then posts a message.
     */
    function createMessageWithAppCredentials() {
      try {
        const service = getService_();
        if (!service.hasAccess()) {
          console.error(service.getLastError());
          return;
        }
    
        // Specify the message to create.
        const message = {'text': 'Hello world!'};
    
        // Call Chat API with a service account to create a message.
        const result = Chat.Spaces.Messages.create(
            message,
            PARENT,
            {},
            // Authenticate with the service account token.
            {'Authorization': 'Bearer ' + service.getAccessToken()});
    
        // Log details about the created message.
        console.log(result);
    
      } catch (err) {
        // TODO (developer) - Handle exception.
        console.log('Failed to create message with error %s', err.message);
      }
    }
    
    /**
     * Configures the OAuth library to authenticate with the service account.
     */
    function getService_() {
      return OAuth2.createService(CREDENTIALS.client_email)
          .setTokenUrl('https://oauth2.googleapis.com/token')
          .setPrivateKey(CREDENTIALS.private_key)
          .setIssuer(CREDENTIALS.client_email)
          .setSubject(CREDENTIALS.client_email)
          .setScope(SCOPE)
          .setPropertyStore(PropertiesService.getScriptProperties());
    }
    
  3. 在程式碼中,將 CREDENTIALS 替換為 credentials.json 檔案的內容。

  4. 在程式碼中,將 SPACE_NAME 替換為聊天室名稱,您可以從 Chat API 的 spaces.list 方法或聊天室網址取得。

步驟 4:執行完整範例

在工作目錄中建構並執行範例:

Java

mvn compile assembly:single
java -jar target/auth-sample-app-1.0-SNAPSHOT-jar-with-dependencies.jar

Python

python3 chat_app_auth.py

Node.js

node chat_app_auth.js

Apps Script

在 Apps Script 編輯器中開啟 ChatAppAuth.gs 檔案,然後按一下「Run」

指令碼會向 Chat API 發出已驗證的要求,這個 API 會以 Chat 應用程式的形式在 Chat 聊天室中發布訊息做為回應。

排解範例問題

本節說明嘗試執行這個範例時可能會遇到的常見問題。

您無法使用這個應用程式

執行指令碼時,您可能會收到以下錯誤訊息:

<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">

這則錯誤訊息表示 Chat 應用程式的權限不足,無法在指定 Chat 聊天室中建立 Chat 訊息。

如要解決這個錯誤,請將 Chat 應用程式新增至指令碼中指定的 Chat 聊天室

如要瞭解 Chat API 還可以執行哪些操作,請參閱 Chat API 的參考說明文件