获取API Key
本文为您介绍通过 Agent 获取 Agent Identity 中存储的 API Key 以访问其他下游服务的认证流程和代码配置方式。
工作流程
完成入站认证。Agent 通过 Agent Identity SDK 调用 Agent Identity 服务的
GetWorkloadAccessToken*系列接口获取 Workload Access Token。常见的入站认证方式是使用外部身份提供商签发的 JWT Token。获取API Key。Agent Identity SDK 使用获取的 Workload Access Token,以 Workload Identity(关联的 RAM 角色)的身份调用 Agent Identity 服务的
GetResourceAPIKey接口,获取 API Key。访问资源。Agent 使用获取的 API Key 访问资源。
使用方式
在 Agent Identity 中创建 API Key 凭证提供商后,即可在 Agent 中使用 Agent Identity SDK 获取 API Key。在使用 API Key 调用其它服务的函数前,添加@requires_api_key注解并传入以下参数。Agent Identity SDK会为您自动获取Workload Access Token并以此请求API Key。
API Key凭证提供商名称:在 Agent Identity 中配置的 API Key 凭证提供商名称。配置方法参见创建API Key凭证提供商。
用户上下文信息(可选):包含 Agent 的用户信息,例如用户 ID、用户令牌(ID Token)。Agent Identity SDK 基于此信息决定如何获取 Workload Access Token。
示例代码(Python):
from agent_identity_python_sdk.identity import requires_api_key
@requires_api_key(
provider_name="<your-api-key-provider-name>",
user_info_context=<your-user-identifier-context> # optional
)
async def weather_search(query: str, api_key: str):
print(f"query: {query}")
if not api_key:
raise Exception("Api key is required")
await call_weather_api(api_key)