自訂權杖代理程式

本指南提供更進階的資訊,說明如何設定、自訂及擴充 Omnichannel Gateway 的權杖代理程式。

權杖代理程式進階概念

自訂權杖代理程式前,請務必詳閱並瞭解權杖代理程式架構和安全模型。

安全憑證中介服務 (第三方憑證中介服務)

根據預設,權杖代理程式會以「公開」模式 (public_issue_method_config) 執行,允許用戶端 SDK 直接連線並要求未經驗證的工作階段權杖。雖然公開模式方便基本部署,但只允許有限的自訂和可調整選項 (本頁面會說明)。舉例來說,由於公開模式中介服務不安全,且是從使用者瀏覽器發出,因此無法注入經過驗證的後設資料 (例如使用者經過驗證的帳戶 ID),也無法有條件地限制權杖核發。

如要支援已驗證的網頁即時通訊工作階段,您可以將權杖代理程式設定為「安全」模式,以便與自訂權杖代理程式搭配運作。

在安全模式下設定權杖代理人時:

  • 閘道會拒絕對未經驗證的 issueToken 端點發出的公開要求 (沒有有效的更新權杖)。

  • 允許從後端向 issueTrustedToken 端點發出經過驗證的要求。這些要求可以在使用者工作階段中填入私人且經過驗證的值。

保護權杖中介服務設定

如要設定權杖代理人拒絕公開要求,請在權杖代理人資源上設定 secured_issue_method_config issue 方法:

{
  "displayName": "Secured Account Broker",
  "issuerServiceAccount": "YOUR_BROKER_SERVICE_ACCOUNT_HERE",
  "securedIssueMethodConfig": {}
}

導入第三方權杖中介服務端點

後端會做為安全的中介仲介服務。並向前端應用程式公開端點。前端要求安全即時通訊權杖時,後端會執行下列操作:

  1. 執行任何使用者驗證檢查 (例如驗證平台上的 Cookie、工作階段或身分識別權杖)。

  2. 執行任何速率限制或防濫用驗證。

  3. 從後端呼叫閘道的 issueTrustedToken 方法,傳遞可代表已驗證工作階段環境的信任聲明,以便核准要求。

呼叫 issueTrustedToken API

從後端服務中,叫用由具備 agenticapplications.omnichannelTokenBrokers.issueTrusted 權限的服務帳戶簽署的 issueTrustedToken API: Google Cloud

Node.js

使用官方 Google Auth Library,透過服務帳戶憑證自動驗證要求:

const { GoogleAuth } = require('google-auth-library');

async function issueTrustedToken() {
  const auth = new GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform']
  });
  const client = await auth.getClient();
  const tokenBrokerName = "projects/PROJECT_ID/locations/LOCATION/omnichannelTokenBrokers/TOKEN_BROKER_ID";
  const url = `https://agenticapplications.googleapis.com/v1alpha/${tokenBrokerName}:issueTrustedToken`;

  const response = await client.request({
    url,
    method: 'POST',
    data: {
      trustedFields: {
        user_id: 'cust_9817231',
        loyalty_tier: 'gold'
      }
    }
  });

  return response.data;
}

Python

使用標準授權輔助模組,透過本機環境應用程式憑證簽署 HTTP POST 要求:

import google.auth
from google.auth.transport.requests import AuthorizedSession

def issue_trusted_token():
    credentials, project = google.auth.default(
        scopes=['https://www.googleapis.com/auth/cloud-platform']
    )
    authed_session = AuthorizedSession(credentials)

    token_broker_name = "projects/PROJECT_ID/locations/LOCATION/omnichannelTokenBrokers/TOKEN_BROKER_ID"
    url = f'https://agenticapplications.googleapis.com/v1alpha/{token_broker_name}:issueTrustedToken'

    response = authed_session.post(
        url,
        json={
            'trustedFields': {
                'user_id': 'cust_9817231',
                'loyalty_tier': 'gold'
            }
        }
    )
    response.raise_for_status()
    return response.json()

curl

直接透過指令列執行一般 HTTP POST 要求,測試代理程式設定:

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  "https://agenticapplications.googleapis.com/v1alpha/projects/PROJECT_ID/locations/LOCATION/omnichannelTokenBrokers/TOKEN_BROKER_ID:issueTrustedToken" \
  -d '{
    "trustedFields": {
      "user_id": "cust_9817231",
      "loyalty_tier": "gold"
    }
  }'
回應內容

閘道會傳回存取權杖、工作階段 ID 和更新權杖參數,這些權杖的效期較短:

{
  "accessToken": "ACCESS_TOKEN_STRING",
  "expireTime": "2026-05-26T20:26:00Z",
  "sessionId": "SESSION_ID_STRING",
  ...
}

您的端點必須將整個回應來回傳送至用戶端瀏覽器 SDK。您不應嘗試檢查或後續處理這個酬載,因為從現在起,這個酬載是由閘道和網路用戶端擁有及管理。

與 WebChat 整合

將預先建構的 WebChat SDK 與安全權杖代理程式整合時,您必須提供自訂權杖解析器,而不是只提供 tokenBrokerName。自訂解析器負責呼叫後端的授權端點,以擷取權杖。

如要設定自訂權杖解析器,請在 createContext 的 tokenBroker 選項中提供 initialAccessTokenResolver:

<script>
  window.addEventListener("chat-messenger-loaded", >async () = {
    // Custom resolver function to fetch the token from your 3P broker
    const customTokenResolver = >async () = {
      const response = await fetch("https://api.yourdomain.com/chat/auth-token", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          // Pass any clientside parameters if needed
        })
      });

      if (!response.ok) {
        throw new Error("Failed to authenticate chat session");
      }
      return response.json();
    };

    const context = await window.chatSdk.prebuilts.omnichannel.createContext({
      tokenBroker: {
        tokenBrokerName: "projects/PROJECT_ID/locations/LOCATION/omnichannelTokenBrokers/TOKEN_BROKER_ID",
        initialAccessTokenResolver: customTokenResolve<r
     > }
    });

    window.chatSdk.registerContext(context);
  });
/script

WebChat SDK 使用自訂解析器成功初始化工作階段後,後端作業會根據要求類型而有所不同:

  • 首次發放:WebChat SDK 會叫用自訂 initialAccessTokenResolver 來取得初始權杖。這會在用戶端設定安全工作階段 ID、初始存取權杖和更新權杖。
  • 背景權杖重新整理:WebChat SDK 會在背景自動管理權杖到期問題。存取權杖到期前約一分鐘,SDK 會直接向公開的閘道端點傳送重新整理要求。並傳遞 refreshToken,以及指定 ACCESS_TOKEN 的授權類型。由於這個流程是由預先簽署的 refreshToken 授權,因此 SDK 不會再次呼叫您的自訂解析器,進行背景重新整理。

後續步驟