本文為您介紹通過 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 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)