使用雙足式 OAuth 和驗證管理工具進行驗證

如要讓代理使用自己的授權向 ServiceNow 或 Salesforce 等外部工具進行驗證,請在 Agent Identity 驗證管理工具中,使用雙足式 OAuth (用戶端憑證) 驗證提供者設定外送驗證。

雙向 OAuth 驗證供應商會為您管理憑證和權杖。這樣就不必編寫自訂程式碼來處理驗證流程。

雙足式 OAuth 工作流程

雙足式 OAuth 授權提供者會使用代理程式的身分,不需要使用者同意。Google 會管理用戶端憑證的儲存空間。使用 Agent Development Kit (ADK) 時,系統會自動擷取產生的存取權杖,並將其插入工具呼叫標頭。

事前準備

  1. 確認您選擇的驗證方法正確無誤
  2. 啟用 Agent Identity Connector API。

    啟用 API 時所需的角色

    如要啟用 API,您需要具備服務使用情形管理員 IAM 角色 (roles/serviceusage.serviceUsageAdmin),其中包含 serviceusage.services.enable 權限。瞭解如何授予角色

    啟用 API

  3. 建立及部署代理程式

  4. 從要連結的第三方應用程式取得用戶端 ID用戶端密鑰

  5. 確認您具備完成這項工作所需的角色

必要的角色

如要取得建立及使用雙向代理程式身分驗證供應商所需的權限,請要求管理員授予您專案的下列 IAM 角色:

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

這些預先定義的角色具備建立及使用雙足式代理程式身分驗證提供者所需的權限。如要查看確切的必要權限,請展開「Required permissions」(必要權限) 部分:

所需權限

如要建立及使用雙向代理程式身分驗證供應商,必須具備下列權限:

  • 如要建立驗證提供者: iamconnectors.connectors.create
  • 如何使用驗證提供者:
    • iamconnectors.connectors.retrieveCredentials
    • aiplatform.endpoints.predict
    • aiplatform.sessions.create

您或許還可透過自訂角色或其他預先定義的角色取得這些權限。

建立 2 向驗證提供者

建立驗證提供者,定義第三方應用程式的設定和憑證。

如要建立雙向驗證授權供應商,請使用 Google Cloud 控制台或 Google Cloud CLI。

控制台

  1. 前往 Google Cloud 控制台的「Agent Registry」頁面。

    前往 Agent Registry

  2. 按一下要建立驗證提供者的代理程式名稱。
  3. 按一下「身分」
  4. 在「Auth Providers」(驗證提供者) 專區中,按一下「新增驗證提供者」
  5. 在「新增驗證供應商」窗格中,輸入名稱和說明。

    名稱只能使用小寫英文字母、數字或連字號,開頭須為小寫英文字母,結尾不得為連字號。

  6. 在「OAuth Type」清單中,選取「OAuth (2 legged)」。 。
  7. 點按「Create and continue」(建立並繼續)
  8. 如要授予代理程式身分使用驗證提供者的權限,請按一下「Grant access」(授予存取權)。

    這會自動將「連結器使用者」(roles/iamconnectors.user) 角色指派給授權提供者資源上的代理程式身分。

  9. 在「Auth provider credentials」(驗證供應商憑證) 專區中,輸入下列資訊:
    • 用戶端 ID
    • 用戶端密碼
    • 權杖網址
  10. 按一下「新增供應商設定」

新建立的驗證供應商會顯示在「驗證供應商」清單中。

gcloud CLI

  1. 建立驗證提供者:

    gcloud alpha agent-identity connectors create AUTH_PROVIDER_NAME \
        --location="LOCATION" \
        --two-legged-oauth-client-id="CLIENT_ID" \
        --two-legged-oauth-client-secret="CLIENT_SECRET" \
        --two-legged-oauth-token-endpoint="TOKEN_ENDPOINT"
  2. 確認驗證供應商顯示在清單中,且狀態為 ENABLED
    gcloud alpha agent-identity connectors list \
       --project="PROJECT_ID" \
       --location="LOCATION"
  3. 授予存取權,允許代理程式和本機開發環境從驗證提供者擷取憑證。如要允許已部署的代理程式和個人使用者帳戶存取驗證供應商,請在驗證供應商資源上授予「連結器使用者」(roles/iamconnectors.user) 角色:

    1. 授予已部署代理的 SPIFFE ID (代理身分) 存取權:

      gcloud alpha agent-identity connectors add-iam-policy-binding AUTH_PROVIDER_NAME \
          --project="PROJECT_ID" \
          --location="LOCATION" \
          --role="roles/iamconnectors.user" \
          --member="principal://agents.global.org-ORGANIZATION_ID.system.id.goog/resources/aiplatform/projects/PROJECT_NUMBER/locations/LOCATION/reasoningEngines/ENGINE_ID"
    2. 授予個人使用者帳戶存取權,以進行本機開發和測試 (adk web):

      gcloud alpha agent-identity connectors add-iam-policy-binding AUTH_PROVIDER_NAME \
          --project="PROJECT_ID" \
          --location="LOCATION" \
          --role="roles/iamconnectors.user" \
          --member="user:USER_EMAIL"

更改下列內容:

  • PROJECT_ID: Google Cloud 專案 ID。
  • LOCATION:部署驗證供應商和代理程式的位置 (例如 us-west1)。
  • AUTH_PROVIDER_NAME:驗證供應商的名稱 (例如 bigquery-mcp-3lo-authprovider)。
  • AUTHORIZATION_URL:授權伺服器網址 (例如 https://accounts.google.com/o/oauth2/v2/auth)。
  • TOKEN_URL:權杖伺服器網址 (例如 https://oauth2.googleapis.com/token)。
  • CLIENT_ID:您從第三方服務產生的 OAuth 用戶端 ID。
  • CLIENT_SECRET:您從第三方服務產生的 OAuth 用戶端密鑰。
  • ORGANIZATION_ID:您的 Google Cloud 機構 ID。
  • PROJECT_NUMBER:您的 Google Cloud 專案編號。
  • ENGINE_ID:已部署的推論引擎代理程式 ID。
  • USER_EMAIL:您的個人使用者帳戶電子郵件地址。

在代理程式碼中進行驗證

如要驗證代理程式,可以使用 ADK。

ADK

在 ADK 中使用 MCP 工具集,在代理的程式碼中參照驗證提供者。

from google.adk.agents.llm_agent import LlmAgent
from google.adk.auth.credential_manager import CredentialManager
from google.adk.integrations.agent_identity import GcpAuthProvider, GcpAuthProviderScheme
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset
from google.adk.auth.auth_tool import AuthConfig

# Register the Google Cloud Auth Provider so the CredentialManager can use it.
CredentialManager.register_auth_provider(GcpAuthProvider())

# Create the Google Cloud Auth Provider scheme using the auth provider's full resource name.
auth_scheme = GcpAuthProviderScheme(
    name="projects/PROJECT_ID/locations/LOCATION/connectors/AUTH_PROVIDER_NAME"
)

# Configure an MCP tool with the authentication scheme.
toolset = McpToolset(
    connection_params=StreamableHTTPConnectionParams(url="https://YOUR_MCP_SERVER_URL"),
    auth_scheme=auth_scheme,
)

# Initialize the agent with the authenticated tools.
agent = LlmAgent(
    name="AGENT_NAME",
    model="gemini-2.5-flash",
    instruction="AGENT_INSTRUCTIONS",
    tools=[toolset],
)

ADK

在代理的程式碼中,使用 ADK 的已驗證函式工具參照驗證提供者。

import httpx
from google.adk.agents.llm_agent import LlmAgent
from google.adk.auth.credential_manager import CredentialManager
from google.adk.integrations.agent_identity import GcpAuthProvider
from google.adk.integrations.agent_identity import GcpAuthProviderScheme
from google.adk.apps import App
from google.adk.auth.auth_credential import AuthCredential
from google.adk.auth.auth_tool import AuthConfig
from google.adk.tools.authenticated_function_tool import AuthenticatedFunctionTool
from vertexai import agent_engines

# First, register Google Cloud auth provider
CredentialManager.register_auth_provider(GcpAuthProvider())

# Create Auth Config
spotify_auth_config = AuthConfig(
    auth_scheme=GcpAuthProviderScheme(
        name=(
            "projects/PROJECT_ID/locations/"
            "LOCATION/connectors/"
            "AUTH_PROVIDER_NAME"
        )
    )
)

# Use the Auth Config in Authenticated Function Tool
spotify_search_track_tool = AuthenticatedFunctionTool(
    func=spotify_search_track, auth_config=spotify_auth_config
)

# Sample function tool
async def spotify_search_track(credential: AuthCredential, query: str) -> str | list:
    token = None
    if credential.http and credential.http.credentials:
        token = credential.http.credentials.token

    if not token:
        return "Error: No authentication token available."

    async with httpx.AsyncClient() as client:
        response = await client.get(
            "https://api.spotify.com/v1/search",
            headers={"Authorization": f"Bearer {token}"},
            params={"q": query, "type": "track", "limit": 1},
        )
        # Add your own logic here

agent = LlmAgent(
    name="AGENT_NAME",
    model="MODEL_NAME",
    instruction="AGENT_INSTRUCTIONS",
    tools=[spotify_search_track_tool],
)

app = App(
    name="APP_NAME",
    root_agent=agent,
)

vertex_app = agent_engines.AdkApp(app_name=app)

ADK

在代理的程式碼中,使用 ADK 的 Agent Registry MCP 工具集參照驗證提供者。

  from google.adk.agents.llm_agent import LlmAgent
from google.adk.auth.credential_manager import CredentialManager
from google.adk.integrations.agent_identity import GcpAuthProvider
from google.adk.integrations.agent_identity import GcpAuthProviderScheme
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset
from google.adk.auth.auth_tool import AuthConfig
from google.adk.integrations.agent_registry import AgentRegistry

# First, register Google Cloud auth provider
CredentialManager.register_auth_provider(GcpAuthProvider())

# Create Google Cloud auth provider scheme by providing Auth Provider full resource name
auth_scheme = GcpAuthProviderScheme(
    name=(
        "projects/PROJECT_ID/locations/"
        "LOCATION/connectors/"
        "AUTH_PROVIDER_NAME"
    )
)

# Set Agent Registry
registry = AgentRegistry(project_id="PROJECT_ID", location="global")

toolset = registry.get_mcp_toolset(
    mcp_server_name=(
        "projects/PROJECT_ID/locations/"
        "global/mcpServers/"
        "agentregistry-00000000-0000-0000-0000-000000000000"
    ),
    auth_scheme=auth_scheme,
)

# Example MCP tool
toolset = McpToolset(
    connection_params=StreamableHTTPConnectionParams(url="MCP_URL"),
    auth_scheme=auth_scheme,
)

agent = LlmAgent(
    name="AGENT_NAME",
    model="MODEL_NAME",
    instruction="AGENT_INSTRUCTIONS",
    tools=[toolset],
)

  

安裝本機測試用的依附元件

如要在虛擬環境中在本機測試代理程式,請安裝下列必要依附元件:

  1. 建立並啟動虛擬環境:
    python3 -m venv env
    source env/bin/activate
  2. 安裝必要套件:
    pip install google-cloud-aiplatform[agent_engines,adk] google-adk[agent-identity]

部署代理

將代理部署至 Google Cloud時,請務必啟用代理身分。

如要部署至 Gemini Enterprise Agent Platform 的 Agent Runtime ,請使用 identity_type=AGENT_IDENTITY 標記:

import vertexai
from vertexai import types
from vertexai.agent_engines import AdkApp

# Initialize the Vertex AI client with v1beta1 API for Agent Identity support
client = vertexai.Client(
    project="PROJECT_ID",
    location="LOCATION",
    http_options=dict(api_version="v1beta1")
)

# Use the proper wrapper class for your Agent Framework (e.g., AdkApp)
app = AdkApp(agent=agent)

# Deploy the agent with Agent Identity enabled
remote_app = client.agent_engines.create(
    agent=app,
    config={
        "identity_type": types.IdentityType.AGENT_IDENTITY,
        "requirements": ["google-cloud-aiplatform[agent_engines,adk]", "google-adk[agent-identity]"],
    },
)

後續步驟