资讯动态

在 ADK-Python 中集成 GCP Agent Identity 认证:API Key、2LO 与 3LO 完整实战

发布时间:2026/9/13 1:52:39 来源:尧图企业网站定制
在 ADK-Python 中集成 GCP Agent Identity 认证API Key、2LO 与 3LO 完整实战【免费下载链接】adk-pythonAn open-source, code-first Python toolkit for building, evaluating, and deploying sophisticated AI agents with flexibility and control.项目地址: https://gitcode.com/GitHub_Trending/ad/adk-python导读本文基于 adk-python 仓库中的 GCP Auth 示例完整讲解如何借助 Google Cloud Agent Identity 凭证服务Credentials Service为 ADK Agent 的工具接入 API Key、2-legged OAuth2LO与 3-legged OAuth3LO三种认证方式。示例以查询 Spotify 曲目 读取私有播放列表 查询 Google Maps 天气为业务场景读者学完后可以掌握GcpAuthProvider的注册方式、GcpAuthProviderScheme的配置要点、AuthenticatedFunctionTool与McpToolset的认证注入方法以及使用adk web与自定义 FastAPI 客户端分别测试无交互认证和交互式授权流程的完整路径。示例概览一个 Agent 集成三类 GCP 认证该示例位于 contributing/samples/integrations/gcp_auth核心文件为 agent.py。它构建了一个名为gcp_auth的 ADK App根 Agent 挂载了三个工具分别对应三种不同的认证形态工具底层认证方式业务能力Google MapsMcpToolsetAPI Key自动注入X-GOOG-API-KEY查询地点/天气Spotify 搜索AuthenticatedFunctionTool2-legged OAuth2LO服务端到服务端调用 Spotify 搜索接口Spotify 私有播放列表AuthenticatedFunctionTool3-legged OAuth3LO代表用户读取私有数据需用户授权从源码结构可以推断示例的测试路线也是按认证复杂度设计的API Key 与 2LO 是无交互流程可直接通过 ADK 官方 Web 客户端运行3LO 涉及用户在浏览器中完成授权因此配套提供了一个自定义 Web 客户端client/main.py来承载完整的授权回调与凭证落库流程。环境准备虚拟环境与依赖安装激活虚拟环境示例推荐使用独立的 Python 虚拟环境cd adk-python python3 -m venv .venv source .venv/bin/activate安装依赖认证能力依赖agent-identity与mcp两个附加组件pip install google-adk[agent-identity,mcp]其中agent-identity组件会引入google-cloud-agentidentitycredentials、google-cloud-iamconnectorcredentials等凭证服务客户端。从源码看若缺少这些依赖模块会直接抛出安装提示Missing required dependencies for Agent Identity Auth Manager. Please install with: pip install google-adk[agent-identity]见 _agent_identity_credentials_provider.py 与 _iam_connector_credentials_provider.py 的 ImportError 分支。认证本地环境ADC 与配额项目运行示例前需要通过 Application Default CredentialsADC让本机身份具备访问凭证服务的权限gcloud auth application-default login export GOOGLE_CLOUD_PROJECTYOUR_GOOGLE_CLOUD_PROJECT gcloud auth application-default set-quota-project $GOOGLE_CLOUD_PROJECT export GOOGLE_GENAI_USE_ENTERPRISEtrue关键点说明运行 Agent 的身份即 ADC 中的账号必须拥有从这些 connector/provider 拉取凭证的 IAM 权限iamconnectors.user一类角色否则会在检索凭证时被拒绝GOOGLE_GENAI_USE_ENTERPRISEtrue用于启用企业版 Gemini 模型接入示例 Agent 默认使用gemini-3.5-flash见 agent.py之后创建的 provider 资源名依赖GOOGLE_CLOUD_PROJECT与GOOGLE_CLOUD_LOCATIONagent.py 会从环境变量组装形如projects/{project}/locations/{location}/authProviders/{id}的资源全名。创建 Auth Providers三种 connector 的 gcloud 命令参照 GCP 官方文档中关于管理 Auth Provider 的说明在gcloud alpha agent-identity下创建三类 connector。请先导出公共参数export GOOGLE_CLOUD_LOCATIONYOUR_GOOGLE_CLOUD_LOCATION export MAPS_API_AUTH_PROVIDER_IDYOUR_MAPS_API_AUTH_PROVIDER_ID export SPOTIFY_2LO_AUTH_PROVIDER_IDYOUR_SPOTIFY_2LO_AUTH_PROVIDER_ID export SPOTIFY_3LO_AUTH_PROVIDER_IDYOUR_SPOTIFY_3LO_AUTH_PROVIDER_ID1. API Key 型 connectorGoogle Mapsgcloud alpha agent-identity connectors create $MAPS_API_AUTH_PROVIDER_ID \ --project$GOOGLE_CLOUD_PROJECT \ --location$GOOGLE_CLOUD_LOCATION \ --api-keyYOUR_API_KEY2. 2LO 型 connectorSpotify 服务端调用2LO 只需客户端凭据与令牌端点不需要用户参与gcloud alpha agent-identity connectors create $SPOTIFY_2LO_AUTH_PROVIDER_ID \ --project$GOOGLE_CLOUD_PROJECT \ --location$GOOGLE_CLOUD_LOCATION \ --two-legged-oauth-client-idOAUTH_CLIENT_ID \ --two-legged-oauth-client-secretOAUTH_CLIENT_SECRET \ --two-legged-oauth-token-endpointOAUTH_TOKEN_ENDPOINT3. 3LO 型 connectorSpotify 用户授权3LO 需要授权端点、令牌端点与允许的 scopegcloud alpha agent-identity connectors create $SPOTIFY_3LO_AUTH_PROVIDER_ID \ --project$GOOGLE_CLOUD_PROJECT \ --location$GOOGLE_CLOUD_LOCATION \ --three-legged-oauth-client-idOAUTH_CLIENT_ID \ --three-legged-oauth-client-secretOAUTH_CLIENT_SECRET \ --three-legged-oauth-authorization-urlAUTHORIZATION_URL \ --three-legged-oauth-token-urlTOKEN_URL \ --allowed-scopesALLOWED_SCOPES注意运行 Agent 的身份ADC必须具备从这些 connector 检索凭证的必要权限请确保账号拥有相应角色后再继续。理解 GcpAuthProvider 的底层路由在深入示例代码前先理解凭证提供者的实现这对排查为什么我的 provider 不生效至关重要。GcpAuthProvider 继承自BaseAuthProvider其内部组合了两个底层实现_IamConnectorCredentialsProvider面向IAM Connector Credentials 服务connector 资源_AgentIdentityCredentialsProvider面向Agent Identity Credentials 服务authProvider 资源。二者的选择依据是auth_scheme.name的正则匹配结果gcp_auth_provider.pyif re.match(r^projects/[^/]/locations/[^/]/connectors/[^/]$, auth_scheme.name): return await self._iam_connector_provider.get_auth_credential(...) return await self._agent_identity_provider.get_auth_credential(...)即资源名含connectors段则走 IAM Connector 服务否则按authProviders资源走 Agent Identity 服务。本示例中的MAPS_API_AUTH_PROVIDER、SPOTIFY_2LO_AUTH_PROVIDER、SPOTIFY_3LO_AUTH_PROVIDER均组装为.../authProviders/...形式因此最终由 Agent Identity 凭证服务负责签发。两个底层 Provider 都遵循相同的状态机源码注释有明确说明API Key一次请求即返回成功直接构造HttpAuth凭证2LO首次返回pending需以 1 秒间隔轮询NON_INTERACTIVE_TOKEN_POLL_INTERVAL_SEC 1.0最长 10 秒NON_INTERACTIVE_TOKEN_POLL_TIMEOUT_SEC 10.03LO返回uri_consent_required携带authorization_uri与consent_nonce由客户端引导用户完成授权。凭证构造时见 _agent_identity_credentials_provider.py若服务返回的是Authorization: Bearer token头则生成schemeBearer的标准 HTTP 凭证若是自定义头则额外注入X-GOOG-API-KEY头这正是API Key 自动注入的机制来源。示例代码拆解四种配置方式完整代码见 agent.py下面按 README 的步骤逐一拆解。1. 注册 GCP Auth Provider将GcpAuthProvider注册进全局CredentialManager使其能够解析gcpAuthProviderScheme类型的认证配置。此操作只需执行一次CredentialManager.register_auth_provider(GcpAuthProvider())对应实现位置为 agent.py。注册后Agent 在运行工具时若遇到GcpAuthProviderSchemeCredentialManager会自动路由到该 Provider 拉取凭证。2. 配置 2LOAuthenticatedFunctionTool先用GcpAuthProviderScheme指向 2LO connector 资源名再把它包装进AuthConfig最后附着到AuthenticatedFunctionToolspotify_auth_config_2lo AuthConfig( auth_schemeGcpAuthProviderScheme(nameSPOTIFY_2LO_AUTH_PROVIDER) ) spotify_search_track_tool AuthenticatedFunctionTool( funcspotify_search_track, auth_configspotify_auth_config_2lo, )其中SPOTIFY_2LO_AUTH_PROVIDER为projects/{project}/locations/{location}/authProviders/{id}全名。2LO 场景不需要scopes与continue_uri因为服务端到服务端的令牌交换由凭证服务代劳。工具函数本身负责消费凭证。以spotify_search_track为例agent.py它接收credential: AuthCredential参数从credential.http中取出 token 组装Authorization头再调用 Spotify 搜索接口async def spotify_search_track(credential: AuthCredential, query: str) - str | list: headers {} if http : credential.http: if http.scheme and http.credentials and (token : http.credentials.token): headers[Authorization] f{http.scheme.title()} {token} if http.additional_headers: headers.update(http.additional_headers) ...AuthConfig定义于 auth_tool.py核心字段为auth_scheme认证方案与exchanged_auth_credential交换后的凭证由 ADK 与客户端协作填充。3. 配置 3LO交互式用户授权3LO 需要用户授权因此GcpAuthProviderScheme必须携带scopes与continue_urispotify_auth_config_3lo AuthConfig( auth_schemeGcpAuthProviderScheme( nameSPOTIFY_3LO_AUTH_PROVIDER, scopes[playlist-read-private], continue_uriCONTINUE_URI, ) ) spotify_get_playlist_tool AuthenticatedFunctionTool( funcspotify_get_playlists, auth_configspotify_auth_config_3lo, )其中CONTINUE_URI http://localhost:8080/commitagent.py它作为 OAuth 完成后的继续 URIGoogle 托管的 OAuth 重定向 URI 会把用户重定向到这里Agent 会在每次 3LO 请求中把该 URI 发给上游凭证服务。从 GcpAuthProviderScheme 的定义可以确认其字段语义字段类型说明type_Literal[gcpAuthProviderScheme]安全方案类型标识alias 为typenamestrGCP Auth Provider 资源全名scopesOptional[List[str]]请求的 OAuth2 作用域3LO 必填continue_uriOptional[str]授权完成后重定向的 URI用于防钓鱼与收尾托管 OAuth 流程开发者必须确保该 URI 可被公网访问可托管在 GCP、第三方云或自建服务器上最好与 Agent 客户端的 Web 服务器同址4. 配置 MCP Toolset 的自动认证当使用McpToolset时直接把auth_scheme传给工具集MCP 服务器通信期间会自动完成认证如 API Key 注入maps_tools McpToolset( connection_paramsStreamableHTTPConnectionParams(urlMAPS_MCP_ENDPOINT), auth_schemeGcpAuthProviderScheme(nameMAPS_API_AUTH_PROVIDER), errlogNone, # Required for agent-freezing (pickling) )两点值得注意MAPS_MCP_ENDPOINT https://mapstools.googleapis.com/mcpagent.py是 Google Maps 工具集的 Streamable HTTP 端点errlogNone是刻意为之示例注释明确说明这是agent 冻结pickling所必需避免日志对象在序列化时引发错误。最后将三个工具挂到根 Agent 并包装为 Approot_agent Agent( namegcp_auth_agent, modelMODEL, instruction( You are a Spotify and Google Maps assistant. Use your tools to search for track details, fetch the users private playlists, and look up locations. ... ), tools[spotify_search_track_tool, spotify_get_playlist_tool, maps_tools], ) app App(namegcp_auth, root_agentroot_agent)注意 README 中 Agent 名称为gcp_auth而 agent.py 中根 Agent 的name为gcp_auth_agentApp 名为gcp_auth——在 ADK Web UI 中应选择名为gcp_auth的应用。三组示例输入与对应的认证链路README 给出了三组可直接验证的输入What is the current weather in New York?走 Google Maps 工具验证API Keyauth provider凭证服务直接返回密钥注入X-GOOG-API-KEY头完成调用。Tell me about the song: Waving Flag走 Spotify 搜索曲目工具验证2LOauth provider凭证服务先返回pending客户端以 1 秒间隔轮询直至令牌签发随后以Bearer头调用 Spotify API。Get my private playlists走 Spotify 私有播放列表工具验证3LOauth provider必须使用自定义 Web 客户端完成浏览器授权授权回调携带consent_nonce调用凭证服务的 Finalize 流程后才能获取令牌。测试一用adk web验证 API Key 与 2LOAPI Key 与 2LO 均为无交互流程直接启动 ADK Web 开发 UI 即可adk web contributing/samples/integrations操作步骤在 ADK Web UI 顶部的应用下拉框中选中gcp_auth依次尝试上文第 1、2 组示例输入分别验证 MapsAPI Key与 Spotify 搜索2LO是否正常返回。adk web启动时会扫描指定目录下的 Agent 定义包括 agent.py因此传入的是其父目录contributing/samples/integrations。测试二用自定义 Web 客户端验证 3LO3LO 需要完整的授权回调闭环示例为此提供了 FastAPI 客户端client/main.py。安装客户端依赖cd contributing/samples/integrations/gcp_auth/client pip install -r requirements.txtrequirements.txt 中除google-adk[agent-identity,mcp]外还包含fastapi、uvicorn、httpx、google-auth以及google-cloud-aiplatform[agent-engines]1.148.1后者用于远程 Agent 引擎的发现与调用。启动客户端uvicorn main:app --port 8080 --reload然后打开http://localhost:8080。注意必须使用localhost而不是127.0.0.1因为 OAuth 重定向 URL 对此有严格要求continue_uri为http://localhost:8080/commit。选择 Agent 类型并加载客户端同时支持本地与远程 Agent见 main.py 的ChatRequest模型Local Agent从下拉框选择本地 Agent 模块如agent。客户端通过AGENT_PROJECT_DIR环境变量默认取 gcp_auth 目录定位模块用InMemoryRunner运行并缓存会话local_runners全局缓存保证多轮对话会话不丢失Remote Agent填入 GCP Project ID 与 Location点击 Load Remote Agents 后选择引擎。客户端通过vertexai.Client(...).agent_engines.list()枚举已部署的 Agent 引擎。3LO 授权闭环的实现细节理解 main.py 能帮你更透彻地明白 3LO 全流程Agent 调用受 3LO 保护的工具时底层凭证服务返回uri_consent_requiredADK 随即发出名为adk_request_credential的函数调用客户端在/chat的 SSE 事件流中侦测到该函数调用main.py解析出auth_uri、consent_nonce与auth_config以popup_auth_uri等字段注入事件前端弹出授权窗口用户在 Google 托管的授权页完成后被重定向到/commit即continue_uri/commit处理器校验 cookie 中的user_id、consent_nonce与查询参数user_id_validation_state、auth_provider_name通过AuthProviderCredentialsServiceClient.finalize_credentials落库凭证main.py并返回Authorization successful页面前端把auth_config作为adk_request_credential的函数响应回传/chatis_auth_resumetrueAgent 据此完成授权恢复随后真正调用 Spotify 私有播放列表接口。从源码可以推断/commit中的auth_provider_name同时兼容connector_name参数并会把路径中的/connectors/规范化为/authProviders/main.py以适配两类凭证服务的资源命名差异。常见问题与注意事项权限不足运行 Agent 的 ADC 身份必须拥有从 connector/authProvider 检索凭证的 IAM 角色否则get_auth_credential会抛出RuntimeError: Failed to retrieve credential ...。依赖缺失务必安装google-adk[agent-identity,mcp]缺少时导入即报错并提示安装命令。回调地址必须用 localhost3LO 的continue_uri绑定http://localhost:8080/commit使用127.0.0.1会导致重定向校验失败。errlogNone不能省略McpToolset未显式设置errlog时可能导致 agent 冻结pickling失败。凭证轮询超时2LO 令牌交换采用 1 秒间隔、10 秒超时的轮询策略源码常量NON_INTERACTIVE_TOKEN_POLL_INTERVAL_SEC/NON_INTERACTIVE_TOKEN_POLL_TIMEOUT_SEC服务端令牌签发较慢时需要适当评估超时窗口。不支持的状态会静默降级两个底层 Provider 对无法识别的服务状态抛出ValueError而非RuntimeError因为BaseLlmFlow._resolve_toolset_auth会捕获ValueError记录日志并继续执行避免一次本可恢复的认证状态直接中断整个调用见 _agent_identity_credentials_provider.py 的注释说明。参考资源示例完整代码contributing/samples/integrations/gcp_auth/agent.py自定义 Web 客户端contributing/samples/integrations/gcp_auth/client/main.pyProvider 实现gcp_auth_provider.py、gcp_auth_provider_scheme.py凭证服务底层实现agent_identity 模块 README、_agent_identity_credentials_provider.py、_iam_connector_credentials_provider.py认证配置模型auth_tool.py认证工具包装authenticated_function_tool.py关于 2LO 与 3LO 的授权细节可进一步查阅 GCP IAM 文档中使用 2LO 认证与使用 3LO 认证的章节本文不再赘述。【免费下载链接】adk-pythonAn open-source, code-first Python toolkit for building, evaluating, and deploying sophisticated AI agents with flexibility and control.项目地址: https://gitcode.com/GitHub_Trending/ad/adk-python创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价