使用驗證管理工具,透過 API 金鑰進行驗證

如要讓代理向 Google 地圖或 Weather API 等外部工具進行驗證,請在 Agent Identity 驗證管理工具中,使用 API 金鑰驗證供應商設定外送驗證。

API 金鑰驗證提供者會為您管理加密編譯金鑰。這項功能可讓您不必在代理程式的程式碼中硬式編碼金鑰,或手動管理金鑰。

API 金鑰工作流程

API 金鑰驗證提供者會使用代理的身分,不需要使用者同意。Google 會採取措施,確保 API 金鑰在儲存期間的安全。使用 Agent Development Kit (ADK) 時,系統會自動擷取 API 金鑰,並插入工具叫用標頭。

事前準備

  1. 確認您選擇了正確的驗證方式。
  2. 啟用 Agent Identity API (如果尚未啟用)。

    啟用 API 所需的角色

    您必須具備 serviceusage.services.enable 權限,才能啟用 API。如果您建立了專案,可能已透過「擁有者」角色 (roles/owner) 取得這項權限。否則,您可以透過「Service Usage 管理員」角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色。

    啟用 API

  3. 建立及部署代理。

  4. 從要連結的第三方服務取得 API 金鑰。

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

必要的角色

如要取得建立及使用 API 金鑰驗證服務供應商所需的權限,請要求管理員授予您專案的下列 IAM 角色:

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

這些預先定義的角色具備建立及使用 API 金鑰驗證供應商所需的權限。如要查看確切的必要權限,請展開「Required permissions」(必要權限) 部分:

所需權限

必須具備下列權限,才能建立及使用 API 金鑰驗證提供者:

  • 如要建立驗證提供者,請按照下列步驟操作: agentidentity.authProviders.create
  • 如要使用驗證提供者:
    • agentidentity.authProviders.retrieveCredentials
    • aiplatform.endpoints.predict
    • aiplatform.sessions.create

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

從第三方服務取得 API 金鑰

建立驗證供應商前,請先從要連結代理的第三方服務取得 API 金鑰。

如果您要連線至 Google Cloud以外的第三方服務,請從該服務的開發人員入口網站取得 API 金鑰,並略過本節步驟。

如要連線至 Google Cloud 服務 (例如 Cloud Translation 或 Google 地圖),請按照下列步驟產生及設定 API 金鑰:

  1. 在 Google Cloud 控制台,為專案啟用必要的 API 服務:

    1. 在 Google Cloud 控制台中,依序前往「APIs & Services」(API 與服務) >「Library」(程式庫) 頁面。

      依序前往「API 和服務」>「程式庫」

    2. 搜尋並啟用代理使用的 API,例如 Cloud Translation API 或 Google Maps Weather API。
    3. 複製產生的 API 金鑰字串。
  2. 設定 API 金鑰:

    1. 在 Google Cloud 控制台中,依序前往「APIs & Services」(API 和服務) >「Credentials」(憑證) 頁面。

      依序前往「APIs & Services」(API 和服務) >「Credentials」(憑證)

    2. 依序點選「建立憑證」>「API 金鑰」。
    3. 在「Create API key」(建立 API 金鑰) 對話方塊中,執行下列操作:
      1. 輸入 API 金鑰的不重複名稱。
      2. 如要將金鑰限制為只能用於您啟用的特定 API,請從「選取 API 限制」清單中選取這些 API。
      3. 選用:在「限制金鑰以降低安全性風險」部分,選取要限制存取權的應用程式類型。
      4. 點選「建立」。
  3. 傳送測試要求至服務端點,驗證 API 金鑰。

    • 如要驗證 Cloud Translation API 金鑰,請執行下列指令:

      curl -X POST \
        -H "Content-Type: application/json" \
        -H "X-goog-api-key: YOUR_API_KEY" \
        -d '{"q": "Hello world", "target": "es"}' \
        "https://translation.googleapis.com/language/translate/v2"

      將 YOUR_API_KEY 替換成您產生的 API 金鑰。

    • 如要驗證 Google Maps Weather API 金鑰,請執行下列指令:

      curl -X GET \
        "https://weather.googleapis.com/v1/currentConditions:lookup?key=YOUR_API_KEY&location.latitude=37.4220&location.longitude=-122.0841"

      將 YOUR_API_KEY 替換成您產生的 API 金鑰。

    如果 API 金鑰有效且設定正確,服務就會傳回要求的資料。

建立 API 金鑰驗證提供者

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

如要建立 API 金鑰驗證提供者,請使用 Google Cloud 控制台、Google Cloud CLI 或 REST API。

控制台

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

    前往「Agent Registry」

  2. 按一下要建立驗證提供者的代理名稱。
  3. 按一下「Identity」。
  4. 在 「驗證提供者」部分,按一下 「 新增驗證提供者」。
  5. 在「Add auth provider」(新增驗證供應商) 窗格中,輸入名稱和說明。

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

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

    這項程序會自動將 Agent Identity 使用者 (roles/agentidentity.user) 角色指派給驗證提供者資源上的代理身分。

  9. 在「驗證供應商憑證」部分,輸入 API 金鑰。
  10. 按一下「Add provider config」。

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

gcloud CLI

  1. 建立驗證提供者:

    gcloud agent-identity auth-providers create AUTH_PROVIDER_NAME \
        --project="PROJECT_ID" \
        --location="LOCATION" \
        --api-key="API_KEY"
  2. 確認驗證提供者顯示在清單中,且狀態為 ENABLED:
    gcloud agent-identity auth-providers list \
       --project="PROJECT_ID" \
       --location="LOCATION"
  3. 授予存取權限,允許代理和本機開發環境從驗證提供者擷取憑證。如要允許部署的代理和個人使用者帳戶存取驗證供應商,請在驗證供應商資源上授予代理身分使用者 (roles/agentidentity.user) 角色:

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

      gcloud agent-identity auth-providers add-iam-policy-binding AUTH_PROVIDER_NAME \
          --project="PROJECT_ID" \
          --location="LOCATION" \
          --role="roles/agentidentity.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 agent-identity auth-providers add-iam-policy-binding AUTH_PROVIDER_NAME \
          --project="PROJECT_ID" \
          --location="LOCATION" \
          --role="roles/agentidentity.user" \
          --member="user:USER_EMAIL"

更改下列內容:

  • PROJECT_ID: Google Cloud 專案 ID。
  • LOCATION:部署驗證提供者和代理程式的位置 (例如 us-west1)。
  • AUTH_PROVIDER_NAME:驗證提供者的名稱 (例如 maps-api-key-authprovider)。
  • API_KEY:您從第三方服務產生的 API 金鑰。
  • ORGANIZATION_ID:您的 Google Cloud 組織 ID。
  • PROJECT_NUMBER:您的 Google Cloud 專案編號。
  • ENGINE_ID:已部署推論引擎代理的 ID。
  • USER_EMAIL:個人使用者帳戶的電子郵件地址。

REST

  1. 建立驗證提供者:

    Agent Identity API 的 authProviders.create 方法會在專案和位置建立 API 金鑰驗證服務供應商。

    使用任何要求資料之前,請先修改下列項目的值:

    • PROJECT_ID:您的 Google Cloud 專案 ID。專案 ID 是英數字串,例如 my-project。
    • LOCATION:部署驗證服務供應商和代理程式的位置 (例如 us-west1)。
    • AUTH_PROVIDER_NAME:驗證供應商的名稱 (例如 maps-api-key-authprovider)。名稱只能包含小寫英文字母、數字或連字號,開頭須為小寫英文字母,結尾不得為連字號。
    • API_KEY:您從第三方服務產生的 API 金鑰。

    HTTP 方法和網址:

    POST https://agentidentity.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/authProviders?authProviderId=AUTH_PROVIDER_NAME

    JSON 要求主體:

    {
      "authProviderTypeParams": {
        "apiKey": {
          "apiKey": "API_KEY"
        }
      }
    }
    

    請展開以下其中一個選項,以傳送要求:

    您應該會收到如下的 JSON 回覆:

    {
      "name": "projects/my-project/locations/us-west1/authProviders/maps-api-key-authprovider",
      "createTime": "2026-04-03T21:15:41.367155Z",
      "updateTime": "2026-04-03T21:15:41.367155Z",
      "authProviderTypeParams": {
        "apiKey": {}
      },
      "state": "ENABLED"
    }
    
  2. 如要允許已部署的代理和個人使用者帳戶從驗證提供者擷取憑證,請在驗證提供者資源上授予 Agent Identity 使用者 (roles/agentidentity.user) 角色:

    Agent Identity API 的 authProviders.setIamPolicy 方法會設定驗證提供者資源的允許政策。

    使用任何要求資料之前,請先修改下列項目的值:

    • PROJECT_ID:您的 Google Cloud 專案 ID。專案 ID 是英數字串,例如 my-project。
    • LOCATION:部署驗證服務供應商和代理程式的位置 (例如 us-west1)。
    • AUTH_PROVIDER_NAME:驗證提供者的名稱。
    • ORGANIZATION_ID:您的 Google Cloud組織 ID。
    • PROJECT_NUMBER:部署代理的 Google Cloud 專案編號 (例如 987654321098)。
    • ENGINE_ID:已部署推論引擎代理的 ID。
    • USER_EMAIL:個人使用者帳戶的電子郵件地址。

    HTTP 方法和網址:

    POST https://agentidentity.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/authProviders/AUTH_PROVIDER_NAME:setIamPolicy

    JSON 要求主體:

    {
      "policy": {
        "bindings": [
          {
            "role": "roles/agentidentity.user",
            "members": [
              "principal://agents.global.org-ORGANIZATION_ID.system.id.goog/resources/aiplatform/projects/PROJECT_NUMBER/locations/LOCATION/reasoningEngines/ENGINE_ID",
              "user:USER_EMAIL"
            ]
          }
        ]
      }
    }
    

    請展開以下其中一個選項,以傳送要求:

    您應該會收到如下的 JSON 回覆:

    {
      "version": 1,
      "etag": "BwYKmjvelug=",
      "bindings": [
        {
          "role": "roles/agentidentity.user",
          "members": [
            "principal://agents.global.org-123456789012.system.id.goog/resources/aiplatform/projects/987654321098/locations/us-west1/reasoningEngines/112233445566778899",
            "user:alex@example.com"
          ]
        }
      ]
    }
    

在代理程式碼中驗證

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

ADK

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

from google.adk.agents import Agent
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 Google Cloud auth provider
CredentialManager.register_auth_provider(GcpAuthProvider())

# Create Google Cloud auth provider scheme
# Note: If using the legacy V1 API, the resource name uses 'connectors'
# instead of 'authProviders': projects/.../connectors/...
auth_scheme = GcpAuthProviderScheme(
    name="projects/PROJECT_ID/locations/LOCATION/authProviders/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 = Agent(
    name="AGENT_NAME",
    model="gemini-2.5-flash",
    instruction="AGENT_INSTRUCTIONS",
    tools=[toolset],
)

範例:連線至 Google 地圖 MCP

以下範例說明如何設定 agent.py,將代理連至 Google 地圖 MCP 伺服器:

import os
from google.adk.agents import Agent
from google.adk.apps import App
from google.adk.auth.credential_manager import CredentialManager
from google.adk.integrations.agent_identity import GcpAuthProvider, GcpAuthProviderScheme
from google.adk.models import Gemini
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset

os.environ["GOOGLE_CLOUD_PROJECT"] = "PROJECT_ID"
os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "True"
os.environ["GOOGLE_API_USE_CLIENT_CERTIFICATE"] = "false"

# Register Google Cloud auth provider for Agent Identity Credentials service
CredentialManager.register_auth_provider(GcpAuthProvider())

maps_auth_scheme = GcpAuthProviderScheme(
    name="projects/PROJECT_ID/locations/LOCATION/authProviders/AUTH_PROVIDER_NAME"
)

maps_tools = McpToolset(
    connection_params=StreamableHTTPConnectionParams(url="https://mapstools.googleapis.com/mcp"),
    auth_scheme=maps_auth_scheme,
    errlog=None,
)

root_agent = Agent(
    name="root_agent",
    model=Gemini(model="gemini-2.5-flash"),
    instruction=(
        "You are a helpful AI assistant designed to provide accurate and useful "
        "information. You can also use your Google Maps tools to look up "
        "locations and directions."
    ),
    tools=[maps_tools],
)

app = App(
    root_agent=root_agent,
    name="AGENT_NAME",
)

ADK

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

import httpx
from google.adk.agents import Agent
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
# Note: If using the legacy V1 API, the resource name uses 'connectors'
# instead of 'authProviders': projects/.../connectors/...
spotify_auth_config = AuthConfig(
    auth_scheme=GcpAuthProviderScheme(
        name="projects/PROJECT_ID/locations/LOCATION/authProviders/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 = Agent(
    name="AGENT_NAME",
    model="gemini-2.5-flash",
    instruction="AGENT_INSTRUCTIONS",
    tools=[spotify_search_track_tool],
)

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

vertex_app = agent_engines.AdkApp(app_name=app)

範例:連線至 Google 地圖 Weather API

以下範例示範 agent.py 設定,使用經過驗證的函式工具,將代理連結至 Google 地圖 Weather API:

import os
import httpx
from google.adk.agents import Agent
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.auth.credential_manager import CredentialManager
from google.adk.integrations.agent_identity import GcpAuthProvider, GcpAuthProviderScheme
from google.adk.models import Gemini
from google.adk.tools.authenticated_function_tool import AuthenticatedFunctionTool

os.environ["GOOGLE_CLOUD_PROJECT"] = "PROJECT_ID"
os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "True"
os.environ["GOOGLE_API_USE_CLIENT_CERTIFICATE"] = "false"

# Register Google Cloud auth provider for Agent Identity Credentials service
CredentialManager.register_auth_provider(GcpAuthProvider())

weather_auth_config = AuthConfig(
    auth_scheme=GcpAuthProviderScheme(
        name="projects/PROJECT_ID/locations/LOCATION/authProviders/AUTH_PROVIDER_NAME"
    )
)

async def get_weather(credential: AuthCredential, latitude: float, longitude: float) -> str | dict:
    """Gets current weather conditions for a location."""
    api_key = None
    if http := credential.http:
        if http.additional_headers and "X-GOOG-API-KEY" in http.additional_headers:
            api_key = http.additional_headers["X-GOOG-API-KEY"]
        elif http.credentials and http.credentials.token:
            api_key = http.credentials.token

    if not api_key:
        return "Error: No API key available from the auth provider."

    params = {"location.latitude": latitude, "location.longitude": longitude, "key": api_key}
    async with httpx.AsyncClient() as client:
        response = await client.get(
            "https://weather.googleapis.com/v1/currentConditions:lookup",
            params=params,
        )
        if response.status_code != 200:
            return f"Error from Weather API: {response.status_code} - {response.text}"
        return response.json()

get_weather_tool = AuthenticatedFunctionTool(
    func=get_weather, auth_config=weather_auth_config
)

root_agent = Agent(
    name="root_agent",
    model=Gemini(model="gemini-2.5-flash"),
    instruction=(
        "You are a helpful AI assistant. You will use your weather tool to "
        "look up current conditions."
    ),
    tools=[get_weather_tool],
)

app = App(
    root_agent=root_agent,
    name="AGENT_NAME",
)

ADK

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

您不必為這個流程建構驗證配置。MCP 伺服器的傳出繫結已記錄要使用的驗證供應商。

from google.adk.agents import Agent
from google.adk.auth.credential_manager import CredentialManager
from google.adk.integrations.agent_identity import GcpAuthProvider
from google.adk.integrations.agent_registry import AgentRegistry

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

# Set Agent Registry. LOCATION must be the same region as the auth provider.
registry = AgentRegistry(project_id="PROJECT_ID", location="LOCATION")

# The auth provider is resolved from the MCP server's outbound binding.
toolset = registry.get_mcp_toolset(
    mcp_server_name=(
        "projects/PROJECT_ID/locations/"
        "LOCATION/mcpServers/"
        "agentregistry-00000000-0000-0000-0000-000000000000"
    ),
)

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

  

部署代理

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

Agent CLI

如果您使用 Agent Development Kit (ADK) 和 Agent CLI,請按照下列步驟部署已啟用代理身分的代理:

  1. 在代理應用程式資料夾中,建立名為 .agent_engine_config.json 的設定檔,啟用代理身分:

    echo '{ "identity_type": "AGENT_IDENTITY" }' > AGENT_NAME/.agent_engine_config.json
  2. 將代理部署至 Gemini Enterprise Agent Platform 的 Agent Runtime:

    uv run adk deploy agent_engine AGENT_NAME \
        --project="PROJECT_ID" \
        --region="LOCATION"

    更改下列內容:

    • AGENT_NAME:代理程式應用程式資料夾的名稱 (例如 maps_agent)。
    • PROJECT_ID:您的 Google Cloud專案 ID。
    • LOCATION:要部署代理程式的支援區域 (例如 us-west1)。

Python SDK

如果使用 Vertex AI Python SDK,透過程式輔助方式部署,請使用 identity_type=AGENT_IDENTITY 旗標:

import vertexai
from vertexai import types
from vertexai.agent_engines import AdkApp
from google.adk.auth.credential_manager import CredentialManager
from google.adk.integrations.agent_identity import GcpAuthProvider

# 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")
)

# Register the auth provider in set_up() so that it runs in the deployed
# container. Use the proper wrapper class for your Agent Framework (for example, AdkApp).
class AuthenticatedAdkApp(AdkApp):
    def set_up(self):
        CredentialManager.register_auth_provider(GcpAuthProvider())
        super().set_up()

app = AuthenticatedAdkApp(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,mcp]>=2.7.1",
        ],
    },
)

更改下列內容:

  • PROJECT_ID:您的 Google Cloud 專案 ID。
  • LOCATION:要部署代理程式的支援的地區 (例如 us-west1)。

後續步驟