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

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

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

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

使用服務帳戶進行驗證時,取得相關資料或執行動作 在 Chat 聊天室中,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,然後點按「建立」JSON

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

  5. 按一下「關閉」

如要進一步瞭解服務帳戶,請參閱 服務帳戶

步驟 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. 在左側的「服務」旁邊,按一下「新增服務」
  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 替換成空格 名稱,可從 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 替換成空格 名稱,可從 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 替換成空格 名稱,可從 spaces.list 取得 方法,或是從聊天室網址複製。請確認 您服務帳戶的私密金鑰檔案名為 credentials.json

Apps Script

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

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

    // 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 替換成空格 名稱,可從 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 檔案,並 按一下「執行」

您的指令碼會向 Chat 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 API,瞭解 Chat API 的其他功能 參考說明文件