ตรวจสอบสิทธิ์เป็นแอป Google Chat

คู่มือนี้จะอธิบายวิธีการตั้งค่าและใช้บัญชีบริการเพื่อเข้าถึง Google Chat API ในนามของแอป Chat อันดับแรก ซึ่งช่วยแนะนำวิธีสร้างบัญชีบริการ จากนั้นจะสาธิตวิธีการ เพื่อเขียนสคริปต์ที่ใช้บัญชีบริการเพื่อตรวจสอบสิทธิ์กับ Chat API และโพสต์ข้อความในพื้นที่ใน 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 APIs

สร้างบัญชีบริการ

หากต้องการสร้างบัญชีบริการ ให้ทำตามขั้นตอนต่อไปนี้

คอนโซล Google Cloud

  1. ในคอนโซล Google Cloud ให้ไปที่เมนู > IAM และ ผู้ดูแลระบบ > บัญชีบริการ

    ไปที่บัญชีบริการ

  2. คลิกสร้างบัญชีบริการ
  3. กรอกรายละเอียดบัญชีบริการ แล้วคลิกสร้างและต่อไป
  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 และ ผู้ดูแลระบบ > บัญชีบริการ

    ไปที่บัญชีบริการ

  2. เลือกบัญชีบริการ
  3. คลิกคีย์ > เพิ่มคีย์ > สร้างคีย์ใหม่
  4. เลือก JSON แล้วคลิกสร้าง

    ระบบจะสร้างคู่คีย์สาธารณะ/ส่วนตัวใหม่และดาวน์โหลดลงใน เป็นไฟล์ใหม่ บันทึกไฟล์ JSON ที่ดาวน์โหลดเป็น credentials.json ใน ไดเรกทอรีที่ใช้งานอยู่ ไฟล์นี้เป็นสำเนาเดียวของคีย์นี้ สำหรับข้อมูลเกี่ยวกับวิธีจัดเก็บ กุญแจของคุณอย่างปลอดภัย โปรดดู การจัดการคีย์ของบัญชีบริการ

  5. คลิกปิด

โปรดดูข้อมูลเพิ่มเติมเกี่ยวกับบัญชีบริการที่ บัญชีบริการ ในเอกสารประกอบ Google Cloud IAM

ขั้นตอนที่ 2: ติดตั้งไลบรารีของไคลเอ็นต์ Google และทรัพยากร Dependency อื่นๆ

ติดตั้งไลบรารีไคลเอ็นต์ของ Google และการอ้างอิงอื่นๆ ที่จำเป็นสำหรับโปรเจ็กต์

Java

วิธีเพิ่มไลบรารีของไคลเอ็นต์ของ Google และทรัพยากร Dependency อื่นๆ ที่จำเป็น สำหรับโครงการ Maven ให้แก้ไขไฟล์ pom.xml ในไดเรกทอรีของโครงการและเพิ่ม ทรัพยากร Dependency ต่อไปนี้

<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

หากคุณยังไม่ได้ติดตั้งไลบรารีของไคลเอ็นต์ Google สำหรับ Python ให้เรียกใช้ คำสั่งต่อไปนี้ในอินเทอร์เฟซบรรทัดคำสั่ง

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

Node.js

ในการเพิ่มไลบรารีไคลเอ็นต์ของ Google ลงในโปรเจ็กต์ Node.js ของคุณ ให้เปลี่ยนไปเป็น ไดเรกทอรีของโปรเจ็กต์และเรียกใช้คำสั่งต่อไปนี้ในอินเทอร์เฟซบรรทัดคำสั่ง

npm install "@googleapis/chat"

Apps Script

ตัวอย่างนี้ใช้ OAuth2 สำหรับไลบรารี Apps Script เพื่อสร้างโทเค็น JWT สำหรับการตรวจสอบสิทธิ์บัญชีบริการ วิธีเพิ่มคลัง กับโปรเจ็กต์ Apps Script ดังนี้

  1. คลิกตัดต่อวิดีโอ ทางด้านซ้าย
  2. คลิกเพิ่มคลังทางด้านซ้ายข้างห้องสมุด
  3. ป้อนรหัสสคริปต์ 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 ใน Chat API หรือจาก URL ของพื้นที่ทำงาน

  4. สร้างไดเรกทอรีย่อยใหม่ชื่อ resources ภายในไดเรกทอรีของโปรเจ็กต์

  5. ตรวจสอบว่าตั้งชื่อไฟล์คีย์ส่วนตัวสำหรับบัญชีบริการแล้ว credentials.json และคัดลอกไปยังไดเรกทอรีย่อย resources

  6. หากต้องการกำหนดค่า Maven ให้รวมไฟล์คีย์ส่วนตัวในแพ็กเกจโปรเจ็กต์ แก้ไขไฟล์ pom.xml ในไดเรกทอรีของโครงการและเพิ่มข้อมูลต่อไปนี้ การกำหนดค่าในส่วน <build>:

    <build>
      <!-- ... existing configurations ... -->
      <resources>
        <resource>
          <directory>resources</directory>
        </resource>
      </resources>
    </build>
    
  7. หากต้องการกำหนดค่า Maven เพื่อรวมทรัพยากร Dependency ในแพ็กเกจโปรเจ็กต์และ เพื่อเรียกใช้คลาสหลักของแอปพลิเคชันของคุณ ให้แก้ไขไฟล์ 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 ใน Chat API หรือจาก URL ของพื้นที่ทำงาน โปรดตรวจสอบว่า ไฟล์คีย์ส่วนตัวสำหรับบัญชีบริการชื่อ 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 ใน Chat API หรือจาก URL ของพื้นที่ทำงาน โปรดตรวจสอบว่า ไฟล์คีย์ส่วนตัวสำหรับบัญชีบริการชื่อ credentials.json

Apps Script

  1. แก้ไขไฟล์ appsscript.json ในเครื่องมือแก้ไข Apps Script และเพิ่มขอบเขต 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 ใน Chat API หรือจาก URL ของพื้นที่ทำงาน

ขั้นตอนที่ 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

เปิดไฟล์ ChatAppAuth.gs ในเครื่องมือแก้ไข Apps Script และ คลิก Run

สคริปต์ของคุณได้ส่งคำขอที่ได้รับการตรวจสอบสิทธิ์ไปยัง 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 ที่ระบุไว้ในสคริปต์

ตรวจสอบ Chat API เพื่อดูว่า Chat API ทำอะไรได้บ้าง เอกสารอ้างอิง