使用 API 密钥通过身份验证管理器进行身份验证

如需让智能体向 Google 地图或 Weather API 等外部工具进行身份验证,请使用 Agent Identity 身份验证管理器中的 API 密钥身份验证提供方配置出站身份验证。

API 密钥身份验证提供方会为您管理加密密钥。借助此功能,您无需在智能体的代码中硬编码密钥,也无需手动管理密钥。

API 密钥工作流

API 密钥身份验证提供方使用智能体的身份,不需要用户同意。 Google 会采取措施帮助保护存储期间的 API 密钥。当您使用智能体开发套件 (ADK) 时,它会自动检索 API 密钥并将其注入到工具调用标头中。

准备工作

  1. 确认您已选择正确的身份验证方法
  2. 启用 Agent Identity API。

    启用 API 所需的角色

    如需启用 API,您需要拥有 serviceusage.services.enable 权限。如果您 创建了项目,则可能已通过 所有者角色 (roles/owner) 拥有此权限。否则,您可以通过 Service Usage Admin 角色 (roles/serviceusage.serviceUsageAdmin) 获取此权限。 了解如何授予角色

    启用 API

  3. 创建并部署智能体

  4. 从要连接的第三方服务获取 API 密钥。

  5. 确认您拥有完成 此任务所需的角色。

所需角色

如需获得创建和使用 API 密钥身份验证提供方所需的权限,请让管理员为您授予项目的以下 IAM 角色:

如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

这些预定义角色包含 创建和使用 API 密钥身份验证提供方所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

如需创建和使用 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 控制台中,前往 API 和服务 > 页面。

      前往“API 和服务”>“库”

    2. 搜索并启用智能体使用的 API,例如 Cloud Translation API 或 Google Maps Weather API。
    3. 复制生成的 API 密钥字符串。
  2. 配置 API 密钥:

    1. 在 Google Cloud 控制台中,前往 API 和服务 >凭据 页面。

      前往“API 和服务”>“凭据”

    2. 依次点击创建凭据>API 密钥
    3. 创建 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 密钥身份验证提供方,请使用 gcloud CLI:

  1. 创建身份验证提供方:

    gcloud alpha agent-identity authProviders create AUTH_PROVIDER_NAME \
        --project="PROJECT_ID" \
        --location="LOCATION" \
        --api-key="API_KEY"
  2. 验证您的身份验证提供方是否显示在列表中,并且其状态为 ENABLED
    gcloud alpha agent-identity authProviders list \
       --project="PROJECT_ID" \
       --location="LOCATION"
  3. 授予访问权限,以允许智能体和本地开发环境 从身份验证提供方检索凭据。如需允许 已部署的智能体和您的个人用户账号访问身份验证 提供方,请在身份验证提供方 资源上授予 Agent Identity User (roles/agentidentity.user) 角色:

    1. 授予对已部署智能体的 SPIFFE ID (Agent Identity) 的访问权限:

      gcloud alpha agent-identity authProviders 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 alpha agent-identity authProviders 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:身份验证提供方的名称(例如 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 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 = LlmAgent(
    name="AGENT_NAME",
    model="gemini-2.5-flash",
    instruction="AGENT_INSTRUCTIONS",
    tools=[toolset],
)

示例:连接到 Google 地图 MCP

以下示例演示了将智能体连接到 Google 地图 MCP 服务器的 agent.py 配置:

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"

# 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.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
# 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 = LlmAgent(
    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 Maps Weather API

以下示例演示了使用经过身份验证的函数工具将智能体连接到 Google Maps Weather API 的 agent.py 配置:

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"

# 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 工具集在智能体的代码中引用身份验证提供方。

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

# 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],
)

  

部署智能体

将智能体部署到 Google Cloud时,请确保已启用 Agent Identity 。

如果您要部署到 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]"],
    },
)

后续步骤