如要授予代理存取權,讓代理代表特定使用者存取外部工具和服務 (例如 Jira 工作或 GitHub 存放區),請在 Agent Identity 驗證管理工具中設定三足式 OAuth 驗證提供者。
3-legged OAuth 驗證提供者會管理憑證和權杖,因此您不必使用自訂程式碼來處理驗證流程。
三足式 OAuth 工作流程
三足式 OAuth 驗證提供者需要使用者同意,因為代理會代表使用者存取資源。
- 提示和重新導向:即時通訊介面會提示使用者登入,然後將使用者重新導向至第三方應用程式的同意聲明頁面。
- 同意聲明和儲存:使用者授予權限後,Agent Identity 驗證管理工具會將產生的 OAuth 權杖儲存在 Google 代管的憑證保管箱。
- 插入:使用 Agent Development Kit (ADK) 時,代理會自動從驗證供應商擷取權杖,並插入工具叫用標頭。
事前準備
- 確認您選擇了正確的驗證方式。
-
啟用 Agent Identity API (如果尚未啟用)。
啟用 API 所需的角色
您必須具備
serviceusage.services.enable權限,才能啟用 API。如果您建立了專案,可能已透過「擁有者」角色 (roles/owner) 取得這項權限。否則,您可以透過「Service Usage 管理員」角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色。 - 建立及部署代理。
- 請確認您有前端應用程式,可處理使用者登入提示,並重新導向至第三方同意聲明頁面。
- 確認您具備完成這項工作所需的角色。
必要的角色
如要取得建立及使用三腳驗證提供者所需的權限,請要求管理員授予您專案的下列 IAM 角色:
- 如要建立驗證提供者,請按照下列步驟操作:
-
如要使用驗證提供者:
- 代理身分使用者 (
roles/agentidentity.user) - Vertex AI 使用者 (
roles/aiplatform.user) - 服務使用情形消費者 (
roles/serviceusage.serviceUsageConsumer)
- 代理身分使用者 (
如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。
這些預先定義的角色具備建立及使用三腳驗證供應商所需的權限。如要查看確切的必要權限,請展開「Required permissions」(必要權限) 部分:
所需權限
您必須具備下列權限,才能建立及使用三腳驗證供應器:
-
如要建立驗證提供者,請按照下列步驟操作:
agentidentity.authProviders.create -
如要使用驗證提供者:
-
agentidentity.authProviders.retrieveCredentials -
aiplatform.endpoints.predict -
aiplatform.sessions.create
-
建立三腳驗證提供者
建立驗證提供者,定義第三方應用程式的設定和憑證。
如要建立三腳驗證提供者,請使用 Google Cloud 控制台、Google Cloud CLI 或 REST API。
控制台
- 前往 Google Cloud 控制台的「Agent Registry」頁面。
- 按一下要建立驗證提供者的代理名稱。
- 按一下「Identity」。
- 在 「驗證提供者」部分,按一下 「 新增驗證提供者」。
-
在「Add auth provider」(新增驗證供應商) 窗格中,輸入名稱和說明。
名稱只能使用小寫英文字母、數字或連字號,開頭須為小寫英文字母,結尾不得為連字號。
- 從「OAuth Type」(OAuth 類型) 清單中,選取「OAuth (3 legged)」(OAuth (三足式))。
- 點按「Create and continue」(建立並繼續)。
- 如要授予代理身分使用驗證提供者的權限,請按一下「Grant access」(授予存取權)。
這項程序會自動將 Agent Identity 使用者 (
roles/agentidentity.user) 角色指派給驗證提供者資源上的代理身分。 - 複製回呼網址。
- 在另一個分頁中,在第三方 OAuth 用戶端應用程式上註冊回呼網址。
- 在「Auth provider credentials」(驗證供應商憑證) 部分,輸入下列資訊:
- 用戶端 ID
- 用戶端密鑰
- 權杖網址
- 授權網址
- 「Default continue URI」(預設接續 URI):選填。輸入預設重新導向 URI,在執行階段未提供接續 URI 時,將使用者重新導向至該位置。
- 按一下「Add provider config」。
新建立的驗證供應商會顯示在「Auth Providers」(驗證供應商) 清單中。
gcloud CLI
-
設定 OAuth 用戶端應用程式,註冊用戶端並取得用戶端 ID 和用戶端密鑰。使用該區段中的範本指定重新導向 URI。
-
使用用戶端憑證建立驗證提供者:
gcloud agent-identity auth-providers create
AUTH_PROVIDER_NAME\ --project="PROJECT_ID" \ --location="LOCATION" \ --three-legged-oauth-client-id="CLIENT_ID" \ --three-legged-oauth-client-secret="CLIENT_SECRET" \ --three-legged-oauth-authorization-url="AUTHORIZATION_URL" \ --three-legged-oauth-token-url="TOKEN_URL" \ --three-legged-oauth-default-continue-uri="DEFAULT_CONTINUE_URI"更改下列內容:
AUTH_PROVIDER_NAME:驗證供應商的名稱。PROJECT_ID:您的 Google Cloud 專案 ID。LOCATION:建立驗證提供者的區域。CLIENT_ID:OAuth 用戶端應用程式的用戶端 ID。CLIENT_SECRET:OAuth 用戶端應用程式的用戶端密鑰。AUTHORIZATION_URL:使用者重新導向至授權伺服器端點,以授予同意聲明。TOKEN_URL:授權伺服器上的權杖交換端點。DEFAULT_CONTINUE_URI:選用。使用者授予同意聲明後,系統會將他們導向預設的重新導向 URI。如果執行階段未提供繼續 URI,系統就會使用這個 URI。
- 確認驗證提供者顯示在清單中,且狀態為
ENABLED:gcloud agent-identity auth-providers list \ --project="
PROJECT_ID" \ --location="LOCATION" -
授予存取權限,允許代理和本機開發環境從驗證提供者擷取憑證。如要允許部署的代理和個人使用者帳戶存取驗證供應商,請在驗證供應商資源上授予代理身分使用者 (
roles/agentidentity.user) 角色:-
授予已部署代理的 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" -
授予個人使用者帳戶存取權,以便在本機開發及測試 (
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:驗證提供者的名稱 (例如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:個人使用者帳戶的電子郵件地址。
REST
-
設定 OAuth 用戶端應用程式,註冊用戶端並取得用戶端 ID 和用戶端密鑰。使用該區段中的範本指定重新導向 URI。
-
建立驗證提供者:
Agent Identity API 的
authProviders.create方法會在專案和位置建立三足式 OAuth 驗證提供者。使用任何要求資料之前,請先修改下列項目的值:
PROJECT_ID:您的 Google Cloud 專案 ID。專案 ID 是英數字串,例如my-project。-
LOCATION:部署驗證服務供應商和代理程式的位置 (例如us-west1)。 -
AUTH_PROVIDER_NAME:驗證供應商的名稱 (例如bigquery-mcp-3lo-authprovider)。名稱只能使用小寫英文字母、數字或連字號,開頭須為小寫英文字母,結尾不得為連字號。 -
CLIENT_ID:您從第三方服務產生的 OAuth 用戶端 ID。 -
CLIENT_SECRET:您從第三方服務產生的 OAuth 用戶端密鑰。 -
AUTHORIZATION_URL:授權伺服器網址 (例如https://accounts.google.com/o/oauth2/v2/auth)。 -
TOKEN_URL:權杖伺服器網址 (例如https://oauth2.googleapis.com/token)。 -
DEFAULT_CONTINUE_URI:選用。如果您未在執行階段提供繼續 URI,則使用者授予同意聲明後,系統會將他們重新導向至預設 URI。
HTTP 方法和網址:
POST https://agentidentity.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/authProviders?authProviderId=AUTH_PROVIDER_NAME
JSON 要求主體:
{ "authProviderTypeParams": { "threeLeggedOauth": { "clientId": "CLIENT_ID", "clientSecret": "CLIENT_SECRET", "authorizationUrl": "AUTHORIZATION_URL", "tokenUrl": "TOKEN_URL", "defaultContinueUri": "DEFAULT_CONTINUE_URI" } } }請展開以下其中一個選項,以傳送要求:
您應該會收到如下的 JSON 回覆:
{ "name": "projects/my-project/locations/us-west1/authProviders/bigquery-mcp-3lo-authprovider", "createTime": "2026-04-03T21:15:41.367155Z", "updateTime": "2026-04-03T21:15:41.367155Z", "authProviderTypeParams": { "threeLeggedOauth": { "clientId": "my-oauth-client-id", "redirectUrl": "https://agentidentitycredentials.googleapis.com/v1/projects/my-project/locations/us-west1/authProviders/bigquery-mcp-3lo-authprovider/oauthcallback", "authorizationUrl": "https://accounts.google.com/o/oauth2/v2/auth", "tokenUrl": "https://oauth2.googleapis.com/token", "defaultContinueUri": "http://localhost:8501/validateUserId" } }, "state": "ENABLED" } -
如要允許已部署的代理和個人使用者帳戶從驗證提供者擷取憑證,請在驗證提供者資源上授予 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" ] } ] }
設定 OAuth 用戶端應用程式
註冊 OAuth 用戶端憑證前,請先向第三方授權伺服器 (例如 Google、GitHub 或 Jira) 取得用戶端 ID 和用戶端密鑰。
如果您要連線至Google Cloud以外的第三方服務,請從該服務的開發人員入口網站取得 OAuth 用戶端憑證,並略過本節步驟。
註冊重新導向 URI
設定 OAuth 用戶端憑證時,您必須註冊驗證服務供應商的專屬回呼重新導向 URI。
使用下列範本建構重新導向 URI:
https://agentidentitycredentials.googleapis.com/v1/projects/
PROJECT_ID/locations/LOCATION/authProviders/AUTH_PROVIDER_NAME/oauthcallback更改下列內容:
PROJECT_ID: Google Cloud 專案 ID。LOCATION:要部署驗證服務供應商的區域 (例如us-west1)。AUTH_PROVIDER_NAME:驗證提供者的名稱。
例如:
https://agentidentitycredentials.googleapis.com/v1/projects/my-project/locations/us-west1/authProviders/bigquery-mcp-3lo-authprovider/oauthcallback
如果您要連線至 Google Cloud 服務 (例如 BigQuery),可以在 Google Cloud 控制台中設定同意畫面,並建立 OAuth 用戶端憑證:
-
設定 OAuth 同意畫面:
- 在 Google Cloud 控制台中,依序前往「APIs & Services」(API 和服務)>「OAuth consent screen」(OAuth 同意畫面) 頁面。
- 在「App information」(應用程式資訊) 部分,輸入應用程式名稱 (例如 BigQuery Manager Application) 和支援電子郵件地址。
- 在「Audience」(目標對象) 部分,選取「Internal」(內部) 或「External」(外部)。
- 輸入聯絡資訊,以便接收通知。
- 詳閱並接受《Google API 服務使用者資料政策》。
- 按一下「完成」。
-
建立 OAuth 用戶端憑證:
- 在 Google Cloud 控制台中,依序前往「APIs & Services」(API 和服務)>「OAuth consent screen」(OAuth 同意畫面) >「Clients」(用戶端) 頁面。
- 依序點選「Create credentials」(建立憑證)>「OAuth client ID」(OAuth 用戶端 ID)。
- 從清單中選取「網頁應用程式」選項。
- 輸入容易辨識的 OAuth 用戶端名稱。
- 在「Authorized redirect URIs」(已授權的重新導向 URI) 專區中,按一下「Add URI」(新增 URI),然後輸入您建構的重新導向 URI。
- 點選「建立」。在「OAuth client created」(已建立 OAuth 用戶端) 對話方塊中,複製產生的「Client ID」(用戶端 ID) 和「Client Secret」(用戶端密鑰) 值。
-
在代理程式碼中驗證
如要驗證代理,您可以使用 ADK,或直接呼叫 Agent Identity API。
要求憑證時,應用程式會指定 continue_uri,使用者授予同意聲明後,系統會將他們重新導向至該網址。如果您在建立驗證提供者時設定了 default_continue_uri,則不一定要在代理程式碼中指定 continue_uri。
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()) # The URI to redirect the user to after consent is granted. # Optional if default_continue_uri is configured on the auth provider. CONTINUE_URI = "https://YOUR_FRONTEND_URL/validateUserId" # Create 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", continue_uri=CONTINUE_URI ) # 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="MODEL_NAME (ex. gemini-2.5-flash)", instruction="AGENT_INSTRUCTIONS", tools=[toolset], )
範例:連線至 BigQuery MCP
以下範例顯示 agent.py 設定,可將代理連至 BigQuery 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 import google.auth from google.genai import types _, project_id = google.auth.default() os.environ["GOOGLE_CLOUD_PROJECT"] = "PROJECT_ID" os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "True" bigquery_mcp_auth_provider_id = "AUTH_PROVIDER_NAME" bigquery_mcp_endpoint = os.environ.get( "BIGQUERY_MCP_ENDPOINT", "https://bigquery.googleapis.com/mcp" ) # Register Google Cloud auth provider CredentialManager.register_auth_provider(GcpAuthProvider()) # URI to redirect user to after consent is granted. CONTINUE_URI = "http://127.0.0.1:8501/validateUserId" bigquery_mcp_auth_scheme = GcpAuthProviderScheme( name=f"projects/{project_id}/locations/LOCATION/authProviders/AUTH_PROVIDER_NAME", scopes=["https://www.googleapis.com/auth/bigquery"], continue_uri=CONTINUE_URI, ) bigquery_mcp_tools = McpToolset( connection_params=StreamableHTTPConnectionParams(url=bigquery_mcp_endpoint), auth_scheme=bigquery_mcp_auth_scheme, errlog=None, ) root_agent = Agent( name="root_agent", model=Gemini( model="gemini-2.5-flash", retry_options=types.HttpRetryOptions(attempts=3), ), instruction=( "You are a helpful AI assistant designed to provide accurate and useful" " information. You can also use your BigQuery MCP tools to look up" " BigQuery data." ), tools=[bigquery_mcp_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()) # The URI to redirect the user to after consent is completed. CONTINUE_URI = "WEB_APP_VALIDATE_USER_URI" # Create Auth Config spotify_auth_config = AuthConfig( auth_scheme=GcpAuthProviderScheme( name="projects/PROJECT_ID/locations/LOCATION/authProviders/AUTH_PROVIDER_NAME", continue_uri=CONTINUE_URI ) ) # 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)
ADK
使用 ADK 中的 Agent Registry MCP 工具組,在代理程式碼中參照驗證提供者。
您不必為這個流程建構驗證配置。MCP 伺服器的傳出繫結已記錄要使用的驗證供應商。傳遞 continue_uri,指定使用者同意後要重新導向的位置。
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()) # The URI to redirect the user to after consent is completed. CONTINUE_URI="WEB_APP_VALIDATE_USER_URI" # 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" ), continue_uri=CONTINUE_URI, ) agent = Agent( name="AGENT_NAME", model="MODEL_NAME", instruction="AGENT_INSTRUCTIONS", tools=[toolset], )
直接呼叫 API
如果未使用 ADK,代理必須呼叫 agentidentitycredentials.retrieveCredentials API 才能取得權杖。
由於這是多步驟 OAuth 流程,代理必須處理作業的生命週期:
- 初始要求:代理呼叫
retrieveCredentials。 - 需要同意聲明:如果使用者未授予同意聲明,API 會傳回包含
uri_consent_required結果的回應。其中包含authorization_uri和consent_nonce。 - 前端重新導向:應用程式必須將使用者重新導向至
authorization_uri。 - 完成:使用者授予同意聲明後,請使用
consent_nonce呼叫FinalizeCredentials,完成流程並取得權杖。
更新用戶端應用程式
如要處理 3-legged OAuth 的使用者登入和重新導向,用戶端應用程式必須執行下列步驟,管理使用者同意聲明並繼續對話:
範例 UI 伺服器
您可以下載並執行使用 uvicorn 的完整範例 UI 伺服器。開始之前,請確認您有 GitHub 帳戶,且已安裝 pip。
如要設定及執行範例 UI 伺服器,請按照下列步驟操作:
-
複製
adk-pythonGitHub 存放區:git clone https://github.com/google/adk-python.git
-
前往存放區並啟用 Python 虛擬環境:
cd adk-python python3 -m venv .venv source .venv/bin/activate
-
前往範例 UI 用戶端目錄:
cd contributing/samples/integrations/gcp_auth/client
-
安裝用戶端依附元件:
pip install -r requirements.txt
-
啟動伺服器前,請設定
AGENT_PROJECT_DIR環境變數,指定代理程式碼所在的目錄。否則,應用程式預設會在用戶端目錄的上層資料夾中尋找代理程式。使用
uvicorn啟動範例 UI 伺服器。請確認通訊埠與 OAuth 用戶端中設定的重新導向 URI 相符:export AGENT_PROJECT_DIR="/path/to/your/agent_project" uvicorn main:app --port 8501 --reload
-
在瀏覽器中開啟
http://localhost:8501。(注意:您必須使用localhost,而非127.0.0.1,因為 OAuth 重新導向網址特別需要localhost主機名稱)。指定設定,按一下「Save & Apply Settings」(儲存並套用設定),然後與代理互動。
自訂 UI 應用程式
如要直接在自訂 UI 應用程式中實作這些功能,請按照下列步驟操作:
處理授權觸發條件
當代理需要使用者同意時,會傳回 adk_request_credential 函式呼叫。應用程式必須攔截這項呼叫,才能啟動使用者授權對話方塊或重新導向。
記錄驗證提供者提供的 consent_nonce,管理工作階段內容。在驗證步驟中,必須使用這個 Nonce 驗證使用者。將 auth_config 和 auth_request_function_call_id 值儲存在工作階段中,以便在使用者同意後繼續流程。
if (fc := get_auth_request_function_call(event_data)): print("--> Authentication required by agent.") try: auth_config = get_auth_config(fc) auth_uri, consent_nonce = handle_adk_request_credential( auth_config, AUTH_PROVIDER_NAME, request.user_id ) if auth_uri: event_data['popup_auth_uri'] = auth_uri fc_id = ( fc.get('id') if isinstance(fc, dict) else getattr(fc, 'id', None) ) event_data['auth_request_function_call_id'] = fc_id event_data['auth_config'] = auth_config.model_dump() # Store session state if session_id: consent_sessions[session_id] = { "user_id": request.user_id, "consent_nonce": consent_nonce } except Exception as e: print(f"Error handling adk_request_credential: {e}") # Optionally, add logic to inform the user about the error. def handle_adk_request_credential(auth_config, auth_provider_name, user_id): ec = auth_config.exchanged_auth_credential if ec and ec.oauth2: oauth2 = ec.oauth2 return oauth2.auth_uri, oauth2.nonce return None, None
導入使用者驗證端點
在網路伺服器上導入驗證端點 (與設定期間提供的 continue_uri URI 相同)。這個端點必須執行下列操作:
- 接收
user_id_validation_state、auth_provider_name和uuid做為查詢參數。 - 從工作階段儲存空間擷取
user_id和consent_nonce值。如果有多個授權流程同時執行,請使用uuid比對正確的工作階段。 - 使用這些參數呼叫驗證供應商的
FinalizeCredentialsAPI。 - 收到成功回應後,請關閉授權視窗。
範例:FastAPI 驗證端點 (main.py)
以下範例顯示完整的 FastAPI 驗證端點,可處理 OAuth 回呼並完成使用者憑證:
@app.api_route("/validateUserId", methods=["GET"]) async def validate_user(request: Request): auth_provider_name = request.query_params.get("auth_provider_name") session_id = request.cookies.get("session_id") session = consent_sessions.get(session_id, {}) payload = { "userId": session.get("user_id"), "userIdValidationState": request.query_params.get( "user_id_validation_state" ), "consentNonce": session.get("consent_nonce"), } base_url = "https://agentidentitycredentials.googleapis.com/v1" finalize_url = f"{base_url}/{auth_provider_name}/credentials:finalize" try: async with httpx.AsyncClient(timeout=30.0) as client: resp = await client.post(finalize_url, json=payload) resp.raise_for_status() except httpx.HTTPError as e: err_text = e.response.text if hasattr(e, "response") else str(e) status = e.response.status_code if hasattr(e, "response") else 500 return HTMLResponse(err_text, status_code=status) return HTMLResponse(""" <script> window.close(); </script> <p>Success. You can close this window.</p> """)
繼續與代理對話
使用者授予同意聲明且授權視窗關閉後,請從工作階段資料中擷取 auth_config 和 auth_request_function_call_id 值。如要繼續對話,請在傳送給代理的新要求中,以 function_response 形式加入這些詳細資料。
if (request.is_auth_resume and session.auth_request_function_call_id and session.auth_config): auth_content = types.Content( role='user', parts=[ types.Part( function_response=types.FunctionResponse( id=session.auth_request_function_call_id, name='adk_request_credential', response=session.auth_config ) ) ], ) # Send message to agent async for event in agent.async_stream_query( user_id=request.user_id, message=auth_content, session_id=session_id, ): # ...
部署代理
將代理部署至 Google Cloud時,請務必啟用 Agent Identity。
Agent CLI
如果您使用 Agent Development Kit (ADK) 和 Agent CLI,請按照下列步驟部署已啟用代理身分的代理:
-
在代理應用程式資料夾中,建立名為
.agent_engine_config.json的設定檔,啟用代理身分:echo '{ "identity_type": "AGENT_IDENTITY" }' >
AGENT_NAME/.agent_engine_config.json -
將代理部署至 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)。