本指南說明如何透過使用者的 Google 憑證使用 OAuth 2.0 來存取 Chat API。以使用者憑證進行驗證和授權後,Chat 應用程式就能代表已驗證使用者存取使用者資料並執行作業。透過對使用者進行驗證,應用程式就具備與該使用者的權限相同的權限,而且能夠執行與該使用者執行相同的動作。
使用使用者憑證驗證及授權 API 呼叫後,Chat 擴充應用程式就能執行以下操作:
- 建立 Chat 聊天室。
- 將使用者加入 Chat 聊天室和群組對話。
- 使用其他 Workspace API 中的使用者資料,例如:
當應用程式執行具有使用者驗證機制的動作 (例如建立聊天室) 時,Google Chat 會顯示歸因訊息,告知使用者為已獲授權的使用者執行該動作的應用程式名稱。
如要進一步瞭解 Chat 擴充應用程式何時需要進行驗證,以及使用何種驗證機制,請參閱 Chat API 驗證與授權總覽中的「必要驗證類型」。
使用全網域委派功能進行驗證和授權
如果您是網域管理員,可以授予全網域授權委派,授權應用程式服務帳戶存取使用者資料,而不需要每位使用者取得同意。設定全網域委派功能後,服務帳戶就能模擬使用者帳戶。雖然服務帳戶是用於驗證,但全網域委派會冒用使用者,因此會視為使用者驗證。任何需要使用者驗證的功能都可以使用全網域委派。
使用管理員權限進行驗證與授權
如果你是網域管理員或具備管理員權限的委派管理員,可以在適用方法的要求中設定 use_admin_access
欄位,透過管理員權限來驗證呼叫 Google Chat API 並授權呼叫。如需更多資訊,請參閱 API 參考說明文件。
請注意,當 Google Chat 應用程式執行具備管理員權限的操作時,Chat 並不會將執行動作的 Chat 應用程式名稱或授權管理員的名稱告知使用者,只會告知使用者這項動作是由機構管理員執行。
先備知識
如要執行本指南中的範例,您必須具備下列先決條件:
- 可存取 Google Chat 的 Google Workspace 帳戶。
- 已啟用並設定 Chat API 的 Google Cloud 專案。如要建立專案並啟用 API,請參閱「建立專案並啟用 API」一文。
- 在 Google Cloud 控制台的 Chat API 設定頁面中設定的 Chat 應用程式。如要建立及設定 Chat 應用程式,請參閱使用 Cloud Functions 建構 Google Chat 應用程式。
此外,您還需要下列特定語言的必備條件:
Java
Python
- Python 3.6 以上版本
- pip 套件管理工具
Node.js
Apps Script
- 連結至您 Google Cloud 專案的 Apps Script 專案。如要初始化 Apps Script 專案,請參閱 Google Apps Script Chat 應用程式快速入門導覽課程。
步驟 1:設定 OAuth 同意畫面、指定範圍及註冊應用程式
當您使用 OAuth 2.0 進行授權時,Google 會向使用者顯示同意畫面,包括專案摘要、專案政策以及要求的授權範圍。設定應用程式的 OAuth 同意畫面,可定義 Google 對使用者和應用程式審查者顯示的內容,並且註冊應用程式以供日後發布。
所有使用 OAuth 2.0 的應用程式都需要同意畫面設定,但您只需要針對 Google Workspace 機構以外使用者使用的應用程式列出範圍。
在 Google Cloud 控制台中,依序點選「選單」圖示 > 「API 和服務」>「OAuth 同意畫面」。
選取應用程式的使用者類型,然後按一下「建立」。
填寫應用程式註冊表單,然後按一下「儲存並繼續」。
按一下「新增或移除範圍」。新增並驗證應用程式需要的授權範圍,請依序按一下「更新」和「儲存並繼續」。
查看應用程式註冊摘要。按一下「Edit」進行變更,或是按一下「Back to Dashboard」。
步驟 2:在 Google Cloud 控制台中建立 OAuth 用戶端 ID 憑證
如要以使用者身分進行驗證,並存取應用程式中的使用者資料,您必須建立一或多個 OAuth 2.0 用戶端 ID。用戶端 ID 可用於向 Google 的 OAuth 伺服器識別單一應用程式。如果應用程式在多個平台 (例如 Android、iOS 和網頁) 上執行,您需要為每個平台分別建立用戶端 ID。
建立 OAuth 用戶端 ID 憑證
選擇您的應用程式類型,瞭解建立 OAuth 用戶端 ID 的具體操作說明:
網頁應用程式
- 在 Google Cloud 控制台中,依序前往「選單」圖示 >「API 和服務」>「憑證」>
- 依序點選「建立憑證」>「OAuth 用戶端 ID」。
- 依序點選「應用程式類型」>「網頁應用程式」。
- 在「名稱」欄位中輸入憑證的名稱。這個名稱只會顯示在 Google Cloud 控制台中。
- 新增與應用程式相關的已授權 URI:
- 用戶端應用程式 (JavaScript):按一下「授權的 JavaScript 來源」下方的「新增 URI」。然後輸入瀏覽器要求的 URI。可識別應用程式可以從哪些網域傳送 API 要求至 OAuth 2.0 伺服器。
- 伺服器端應用程式 (Java、Python 等):按一下「已授權的重新導向 URI」下方的「新增 URI」。然後輸入端點 URI,讓 OAuth 2.0 伺服器傳送回應。
- 按一下「建立」,畫面上會顯示 OAuth 用戶端建立的畫面,其中顯示新的用戶端 ID 和用戶端密鑰。
記下用戶端 ID。用戶端密碼不適用於網頁應用程式,
- 按一下「OK」(確定)。新建立的憑證會顯示在「OAuth 2.0 用戶端 ID」之下。
Android
- 在 Google Cloud 控制台中,依序前往「選單」圖示 >「API 和服務」>「憑證」>
- 依序點選「建立憑證」>「OAuth 用戶端 ID」。
- 依序點選「應用程式類型」>「Android」。
- 在「名稱」欄位中輸入憑證的名稱。這個名稱只會顯示在 Google Cloud 控制台中。
- 在「Package name」(套件名稱) 欄位中,輸入
AndroidManifest.xml
檔案中的套件名稱。 - 在「SHA-1 憑證指紋」欄位中,輸入您產生的 SHA-1 憑證指紋。
- 按一下「建立」,畫面上會顯示 OAuth 用戶端建立的畫面,其中顯示您的新用戶端 ID。
- 按一下「OK」(確定)。新建立的憑證會顯示在「OAuth 2.0 用戶端 ID」之下。
iOS
- 在 Google Cloud 控制台中,依序前往「選單」圖示 >「API 和服務」>「憑證」>
- 依序點選「建立憑證」>「OAuth 用戶端 ID」。
- 依序點選「應用程式類型」>「iOS」。
- 在「名稱」欄位中輸入憑證的名稱。這個名稱只會顯示在 Google Cloud 控制台中。
- 在「Bundle ID」欄位中,輸入應用程式
Info.plist
檔案中列出的軟體包 ID。 - 選用:如果您的應用程式顯示在 Apple App Store 中,請輸入 App Store ID。
- 選用:在「團隊 ID」欄位中,輸入由 Apple 產生並指派給團隊的專屬 10 個字元字串。
- 按一下「建立」,系統隨即會顯示已建立 OAuth 用戶端的畫面,並顯示您的新用戶端 ID 和用戶端密鑰。
- 按一下「OK」(確定)。新建立的憑證會顯示在「OAuth 2.0 用戶端 ID」之下。
Chrome 應用程式
- 在 Google Cloud 控制台中,依序前往「選單」圖示 >「API 和服務」>「憑證」>
- 依序點選「建立憑證」>「OAuth 用戶端 ID」。
- 依序按一下「應用程式類型」>「Chrome 應用程式」。
- 在「名稱」欄位中輸入憑證的名稱。這個名稱只會顯示在 Google Cloud 控制台中。
- 在「應用程式 ID」欄位中,輸入應用程式不重複的 32 個字元 ID 字串。您可以在應用程式的 Chrome 線上應用程式商店網址和 Chrome 線上應用程式商店開發人員資訊主頁中找到這個 ID 值。
- 按一下「建立」,系統隨即會顯示已建立 OAuth 用戶端的畫面,並顯示您的新用戶端 ID 和用戶端密鑰。
- 按一下「OK」(確定)。新建立的憑證會顯示在「OAuth 2.0 用戶端 ID」之下。
電腦版應用程式
- 在 Google Cloud 控制台中,依序前往「選單」圖示 >「API 和服務」>「憑證」>
- 依序點選「建立憑證」>「OAuth 用戶端 ID」。
- 依序按一下「應用程式類型」>「電腦版應用程式」。
- 在「名稱」欄位中輸入憑證的名稱。這個名稱只會顯示在 Google Cloud 控制台中。
- 按一下「建立」,系統隨即會顯示已建立 OAuth 用戶端的畫面,並顯示您的新用戶端 ID 和用戶端密鑰。
- 按一下「OK」(確定)。新建立的憑證會顯示在「OAuth 2.0 用戶端 ID」之下。
電視和受限制的輸入裝置
- 在 Google Cloud 控制台中,依序前往「選單」圖示 >「API 和服務」>「憑證」>
- 依序點選「建立憑證」>「OAuth 用戶端 ID」。
- 依序按一下「應用程式類型」>「電視和受限制的輸入裝置」。
- 在「名稱」欄位中輸入憑證的名稱。這個名稱只會顯示在 Google Cloud 控制台中。
- 按一下「建立」,系統隨即會顯示已建立 OAuth 用戶端的畫面,並顯示您的新用戶端 ID 和用戶端密鑰。
- 按一下「OK」(確定)。新建立的憑證會顯示在「OAuth 2.0 用戶端 ID」之下。
通用 Windows 平台 (UWP)
- 在 Google Cloud 控制台中,依序前往「選單」圖示 >「API 和服務」>「憑證」>
- 依序點選「建立憑證」>「OAuth 用戶端 ID」。
- 依序點選「應用程式類型」>「通用 Windows 平台 (UWP)」。
- 在「名稱」欄位中輸入憑證的名稱。這個名稱只會顯示在 Google Cloud 控制台中。
- 在「Store ID」欄位中,輸入應用程式專屬的 12 個字元 Microsoft Store ID 值。您可以在應用程式的 Microsoft Store 網址和合作夥伴中心找到這個 ID。
- 按一下「建立」,系統隨即會顯示已建立 OAuth 用戶端的畫面,並顯示您的新用戶端 ID 和用戶端密鑰。
- 按一下「OK」(確定)。新建立的憑證會顯示在「OAuth 2.0 用戶端 ID」之下。
下載用戶端密鑰 JSON 檔案
用戶端密鑰檔案是 OAuth 用戶端 ID 憑證的 JSON 表示法,Chat 應用程式在提供憑證時可以參照。
在 Google Cloud 控制台中,依序點選「選單」圖示 >「API 和服務」>「Credentials」(憑證)>
在「OAuth 2.0 用戶端 ID」之下,按一下您建立的用戶端 ID。
按一下「Download JSON」。
將檔案儲存為
client_secrets.json
。
步驟 3:安裝 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.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.34.1</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-oauthlib
Node.js
如要將 Google 用戶端程式庫和其他必要的依附元件新增至 Node.js 專案,請切換至專案的目錄,然後在指令列介面中執行下列指令:
npm install "@googleapis/chat" open server-destroy
Apps Script
這個範例使用進階 Chat 服務來呼叫 Google Chat API。如要為 Apps Script 專案開啟服務,請按照下列步驟操作:
- 按一下左側的「編輯器」圖示 。
- 在左側的「Service」(服務) 旁邊,按一下「Add a service」(新增服務) 。
- 選取「Google Chat API」。
- 在「版本」中選取「v1」。
- 按一下「新增」。
您可以使用用戶端程式庫支援的任何語言。
步驟 4:編寫呼叫 Chat API 的指令碼
使用 OAuth 授權呼叫 API 需要完成多個步驟。在網頁或電腦版應用程式中,程序通常如下:
- 應用程式將使用者導向授權頁面,要求存取授權範圍指定的使用者資料。應用程式會透過用戶端 ID 憑證識別本身。
- 使用者查看應用程式要求的權限並核准要求。
- Google 的驗證伺服器會將瀏覽器重新導向至應用程式的 HTTP 端點,並提供授權碼。
- 應用程式會傳送另一個要求至 Google 的授權伺服器,以交換存取權杖的授權碼。
- 應用程式使用存取權杖,代表使用者呼叫 API。
如要進一步瞭解 OAuth 授權程序,請參閱使用 OAuth 2.0 存取 Google API 指南。
下列 Java、Python 和 Node.js 的程式碼範例使用用戶端程式庫執行 OAuth 授權流程。它會開啟本機 HTTP 伺服器,從授權伺服器接收傳回授權碼,然後由授權伺服器交換存取權杖。在 Apps Script 程式碼範例中,這個授權流程由 Apps Script 處理。
完成驗證流程後,指令碼會使用使用者的存取權杖透過 Chat API 進行驗證,然後建立聊天室。
Java
- 在專案的目錄中開啟
src/main/java/com/google/chat/app/authsample/App.java
檔案。 將
App.java
中的內容替換為下列程式碼:package com.google.chat.app.authsample; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.client.util.store.FileDataStoreFactory; import com.google.api.services.chat.v1.HangoutsChat; import com.google.api.services.chat.v1.model.Space; import java.io.InputStreamReader; import java.util.Collection; import java.util.Collections; /** * Authenticates with Chat API via user credentials, then creates a Chat space. */ public class App { // Application OAuth credentials. private static final String KEYS_RESOURCE_URI = "/client_secrets.json"; // Define your app's authorization scopes. private static final Collection<String> SCOPES = Collections.singleton("https://www.googleapis.com/auth/chat.spaces.create"); // Directory to store user credentials. private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".store/auth-sample-app"); // Global instance of the JSON factory. private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); // Global instance of the HTTP transport. private static HttpTransport httpTransport; // Global instance of the DataStoreFactory. The best practice is to make it a single // globally shared instance across your application. private static FileDataStoreFactory dataStoreFactory; public static void main( String[] args ) { try { // Run app. httpTransport = GoogleNetHttpTransport.newTrustedTransport(); dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR); Credential userCredential = authorize(); Space response = App.createChatSpace(userCredential); // Print details about the created space. System.out.println(response); } catch (Exception e) { e.printStackTrace(); } } /** * Authorizes the installed application to access user's protected data. */ private static Credential authorize() throws Exception { // Load client secrets. GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(App.class.getResourceAsStream("/client_secrets.json"))); // Set up authorization code flow. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( httpTransport, JSON_FACTORY, clientSecrets, SCOPES) .setDataStoreFactory(dataStoreFactory) .build(); // Authorize. return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); } /** * Creates a Chat space. */ private static Space createChatSpace(Credential userCredential) throws Exception { // Build the Chat API client and authenticate with the user account. HangoutsChat chatService = new HangoutsChat.Builder( httpTransport, JSON_FACTORY, userCredential) .setApplicationName("auth-sample-app") .build(); // Create a Chat space. Space space = new Space() // To create a named space, set spaceType to SPACE. .setSpaceType("SPACE") // The user-visible name of the space. .setDisplayName("API-made"); return chatService.spaces().create(space).execute(); } }
在專案的目錄中建立名為
resources
的新子目錄。將檔案
client_secrets.json
複製到resources
子目錄。若要設定 Maven 以在專案套件中加入用戶端密鑰檔案,請編輯專案目錄中的
pom.xml
檔案,並將下列設定新增至<build>
區段:<build> <!-- ... existing configurations ... --> <resources> <resource> <directory>resources</directory> </resource> </resources> </build>
如要設定 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
將下列程式碼儲存在名為
chat_space_create_named.py
的檔案內,該檔案位於保留client_secrets.json
的相同目錄中:from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build # 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.spaces.create"] def main(): ''' Authenticates with Chat API via user credentials, then creates a Chat space. ''' flow = InstalledAppFlow.from_client_secrets_file( 'client_secrets.json', SCOPES) creds = flow.run_local_server() # Build a service endpoint for Chat API. service = build('chat', 'v1', credentials=creds) # Use the service endpoint to call Chat API. result = service.spaces().create( # Details about the space to create. body = { # To create a named space, set spaceType to SPACE. 'spaceType': 'SPACE', # The user-visible name of the space. 'displayName': 'API-made' } ).execute() # Prints details about the created space. print(result) if __name__ == '__main__': main()
Node.js
將下列程式碼儲存至名為
chat_space_create_named.js
的檔案,該檔案位於保存 Node.js 專案和client_secrets.json
的相同目錄中:const fs = require('fs'); const path = require('path'); const http = require('http'); const url = require('url'); const destroyer = require('server-destroy'); const chat = require('@googleapis/chat'); // Application OAuth credentials. const keys = require('./client_secrets.json').installed; // Define your app's authorization scopes. // When modifying these scopes, delete the file token.json, if it exists. const scopes = ["https://www.googleapis.com/auth/chat.spaces.create"]; // Create a new OAuth2 client with the configured keys. const oauth2Client = new chat.auth.OAuth2( keys.client_id, keys.client_secret, 'http://localhost:3000' ); /** * Opens an HTTP server to accept the OAuth callback. * In this simple example, the only request to our webserver is to /?code=<code>. */ async function authenticate(scopes) { const opn = (await import('open')).default; return new Promise((resolve, reject) => { // Generate the URL for authorization. const authorizeUrl = oauth2Client.generateAuthUrl({ access_type: 'offline', scope: scopes.join(' '), }); // Start the HTTP server to listen for the callback. const server = http .createServer(async (req, res) => { try { const qs = new url.URL(req.url, 'http://localhost:3000').searchParams; res.end('Authentication successful! Please return to the console.'); server.destroy(); const { tokens } = await oauth2Client.getToken(qs.get('code')); oauth2Client.credentials = tokens; resolve(oauth2Client); } catch (e) { reject(e); } }) .listen(3000, () => { // Open the browser to the authorize URL to start the workflow. opn(authorizeUrl, { wait: false }).then(cp => cp.unref()); }); destroyer(server); }); } /** * Authenticates with Chat API via user credentials, then creates a Chat space. */ async function createSpace() { // Create the Chat API client and authenticate with the authorized user. const chatClient = await chat.chat({ version: 'v1', auth: oauth2Client }); // Call the Chat API to create a space. const result = await chatClient.spaces.create({ // Details about the space to create. requestBody: { // To create a named space, set spaceType to SPACE. 'spaceType': 'SPACE', // The user-visible name of the space. 'displayName': 'API-made' } }); return result; } // Authenticate the user, execute the function, // then print details about the created space. authenticate(scopes) .then(createSpace) .then(console.log);
Apps Script
在 Apps Script 編輯器中編輯
appsscript.json
檔案,並新增呼叫 API 所需的 OAuth 範圍:"oauthScopes": [ "https://www.googleapis.com/auth/chat.spaces.create" ]
將下列程式碼儲存在 Apps Script 專案中名為
ChatSpaceCreateNamed.gs
的檔案:/** * Authenticates with Chat API via user credentials, then creates a * Chat space. */ function createSpace() { try { // Details about the space to create. // To create a named space, set spaceType to SPACE. // The user-visible name of the space is displayName. const space = {'displayName': 'API-made', 'spaceType': 'SPACE'}; // Call Chat API with user credentials to create the space. const result = Chat.Spaces.create(space); // Log details about the created space. console.log(result); } catch (err) { // TODO (developer) - Handle exception console.log('Failed to create space with error %s', err.message); } }
步驟 5:執行範例指令碼
如要執行範例,請從指令列前往存放專案檔案的目錄,然後執行下列指令:
Java
mvn compile assembly:single
java -jar target/auth-sample-app-1.0-SNAPSHOT-jar-with-dependencies.jar
Python
python3 chat_space_create_named.py
Node.js
node chat_space_create_named.js
Apps Script
在 Apps Script 編輯器中開啟 ChatSpaceCreateNamed.gs
檔案,然後按一下「Run」。
瀏覽器會隨即開啟,並提示您登入 Google 帳戶:
您登入後,會出現 OAuth 同意畫面,要求您授予權限給應用程式。
在您授予權限後,指令碼會呼叫 Chat API,這個 API 會使用顯示名稱 API-made
建立 Chat 聊天室做為回應。主控台會顯示 API 呼叫的詳細資料。如要尋找聊天室,請前往 Google Chat 的「聊天室」面板。
排解範例問題
執行 chat_space_create_named.py
時,您可能會收到以下錯誤訊息:
Expected a JSON object with a single property for a "web" or "installed" application
這個錯誤訊息表示您從 Google Cloud 控制台下載的 client_secrets.json
檔案不是以 "web"
或 "installed"
屬性開頭。使用下載檔案進行驗證後,如果您的程式碼並未將存取權杖儲存至 token.json
等新檔案,則存取權杖會寫入 client_secrets.json
,這可能導致在後續的授權嘗試期間發生這項錯誤。
如要解決錯誤,請再次從 Google Cloud 控制台下載用戶端密鑰檔案,然後將新檔案儲存在目前檔案的位置。
相關主題
如果應用程式需要在單一流程的範圍外繼續使用使用者權杖,可以儲存權杖,以便之後重複使用。在這種情況下,您的應用程式需要安全處理使用者權杖,並處理更新權杖撤銷和到期時間。詳情請參閱使用 OAuth 2.0 最佳做法指南。
如要瞭解 Chat API 還可以執行哪些操作,請參閱 Chat API 參考說明文件。