本指南說明如何透過使用者的 Google 憑證使用 OAuth 2.0 以存取 Chat API。使用使用者憑證進行驗證及授權可讓 Chat 應用程式代表已驗證使用者存取使用者資料,並執行作業。以使用者身分進行驗證,應用程式就會擁有與該使用者相同的權限,而且可以執行的操作就像該使用者執行操作一樣。
透過使用者憑證驗證並授權 API 呼叫後,Chat 應用程式可以執行以下操作:
- 建立 Chat 聊天室。
- 將使用者加入 Chat 聊天室和群組對話。
- 使用其他 Workspace API 中的使用者資料,例如:
當應用程式執行設有使用者驗證機制的動作 (例如建立聊天室) 時,Google Chat 會顯示歸因訊息,向使用者顯示歸因訊息,指出執行動作的應用程式名稱 (適用於獲得授權的使用者)。
如要進一步瞭解即時通訊應用程式需要驗證的時機,以及要使用哪種驗證方式,請參閱 Chat API 驗證和授權總覽中的必要驗證類型一節。
如果您是網域管理員,可以授予全網域授權委派權限,藉此授權應用程式的服務帳戶存取您使用者的資料,而無需每位使用者同意。設定全網域委派後,服務帳戶就可以模擬使用者帳戶。雖然會使用服務帳戶進行驗證,但全網域委派會模擬使用者,因此會被視為「使用者驗證」。任何需要使用者驗證的功能都可以使用全網域委派。
必要條件
如要執行本指南中的範例,您需要具備以下條件:
- 擁有可存取 Google Chat 的 Google Workspace 帳戶。
- 已啟用 Chat API 的 Google Cloud 專案。如要建立專案並啟用 API,請參閱「建立專案並啟用 API」。
- 此即時通訊應用程式是在 Google Cloud 控制台的 Chat API 設定頁面中設定。如要建立並設定 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 同意畫面」。
選取應用程式的使用者類型,然後按一下「Create」。
填寫應用程式註冊表單,然後按一下「儲存並繼續」。
按一下「新增或移除範圍」。新增並驗證應用程式所需的授權範圍,按一下「Update」,然後點選「Save and Continue」。
查看您的應用程式註冊摘要。請按一下 [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。此屬性可識別應用程式可從哪些網域向 OAuth 2.0 伺服器傳送 API 要求。
- 伺服器端應用程式 (Java、Python 等):在「授權的重新導向 URI」下方,按一下「新增 URI」。然後輸入端點 URI,OAuth 2.0 伺服器可將回應傳送至這個 URI。
- 按一下「建立」,畫面上會顯示 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 控制台中。
- 在「商店 ID」欄位中,輸入應用程式不重複的 Microsoft Store ID 值,長度為 12 個字元。您可以在應用程式的 Microsoft Store 網址和合作夥伴中心找到這個 ID。
- 按一下「建立」,畫面上會顯示 OAuth 用戶端已建立的畫面,顯示您的新用戶端 ID 與用戶端密鑰。
- 按一下「OK」(確定)。新建立的憑證會顯示在「OAuth 2.0 用戶端 ID」下方。
下載用戶端密鑰 JSON 檔案
用戶端密鑰檔案是 JSON 表示法,聊天應用程式提供憑證時可以參照的 OAuth 用戶端 ID 憑證。
在 Google Cloud 控制台中,依序點選「選單」圖示 >「API 和服務」>「憑證」。
在「OAuth 2.0 用戶端 ID」下方,按一下您建立的用戶端 ID。
按一下「Download JSON」。
將檔案儲存為
client_secrets.json
。
步驟 3:安裝 Google 用戶端程式庫和其他依附元件
安裝專案所需的 Google 用戶端程式庫和其他依附元件。
Java
如要為 Maven 專案新增 Google 用戶端程式庫和其他必要的依附元件,請編輯專案目錄中的 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
如要在 Node.js 專案中新增 Google 用戶端程式庫和其他必要的依附元件,請切換至專案目錄,並在指令列介面中執行下列指令:
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 的其他功能。