如要授予代理存取權,讓代理代表特定使用者存取外部工具和服務 (例如 Jira 工作或 GitHub 存放區),請在 Agent Identity 驗證管理工具中設定三足式 OAuth 驗證提供者。
三足式 OAuth 驗證提供者會為您管理使用者重新導向和權杖。這樣一來,您就不必編寫自訂程式碼來處理複雜的 OAuth 2.0 流程。
三足式 OAuth 工作流程
三足式 OAuth 驗證提供者需要使用者同意,因為代理會代表使用者存取資源。
- 提示和重新導向:即時通訊介面會提示使用者登入,然後將使用者重新導向至第三方應用程式的同意聲明頁面。
- 同意聲明和儲存:使用者授予權限後,Agent Identity 驗證管理工具會將產生的 OAuth 權杖儲存在 Google 代管的憑證保管箱。
- 插入:使用 Agent Development Kit (ADK) 時,代理會自動從驗證供應商擷取權杖,並插入工具叫用標頭。
事前準備
- 確認您選擇了正確的驗證方式。
-
啟用 Agent Identity Connector API (如果尚未啟用)。
啟用 API 所需的角色
您必須具備
serviceusage.services.enable權限,才能啟用 API。如果您建立了專案,可能已透過「擁有者」角色 (roles/owner) 取得這項權限。否則,您可以透過「Service Usage 管理員」角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色。 - 建立及部署代理。
- 請確認您有前端應用程式,可處理使用者登入提示,並重新導向至第三方同意聲明頁面。
- 確認您具備完成這項工作所需的角色。
必要的角色
如要取得建立及使用三腳驗證提供者所需的權限,請要求管理員授予您專案的下列 IAM 角色:
-
如要建立驗證提供者,請按照下列步驟操作:
- IAM 連接器管理員 (
roles/iamconnectors.admin) - IAM 連接器編輯者 (
roles/iamconnectors.editor)
- IAM 連接器管理員 (
-
如要使用驗證提供者:
- IAM 連接器使用者 (
roles/iamconnectors.user) - 服務使用情形消費者 (
roles/serviceusage.serviceUsageConsumer)
- IAM 連接器使用者 (
如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。
這些預先定義的角色具備建立及使用三腳驗證供應商所需的權限。如要查看確切的必要權限,請展開「Required permissions」(必要權限) 部分:
所需權限
您必須具備下列權限,才能建立及使用三腳驗證供應器:
-
如要建立驗證提供者,請按照下列步驟操作:
iamconnectors.connectors.create -
如要使用驗證提供者:
-
iamconnectors.connectors.retrieveCredentials -
aiplatform.endpoints.predict -
aiplatform.sessions.create
-
建立三腳驗證提供者
建立驗證提供者,定義第三方應用程式的設定和憑證。
如要建立三腳驗證提供者,請使用 Google Cloud 控制台或 Google Cloud CLI。
控制台
- 前往 Google Cloud 控制台的「Agent Registry」頁面。
- 按一下要建立驗證提供者的代理名稱。
- 按一下「Identity」。
- 在「驗證提供者」部分,按一下「 新增驗證提供者」。
-
在「Add auth provider」(新增驗證供應商) 窗格中,輸入名稱和說明。
名稱只能使用小寫英文字母、數字或連字號,開頭須為小寫英文字母,結尾不得為連字號。
- 從「OAuth Type」(OAuth 類型) 清單中,選取「OAuth (3 legged)」(OAuth (三足式))。
- 點按「Create and continue」(建立並繼續)。
- 如要授予代理身分使用驗證提供者的權限,請按一下「Grant access」(授予存取權)。
系統會自動將連接器使用者 (
roles/iamconnectors.user) 角色指派給驗證提供者資源上的代理身分。 - 複製回呼網址。
- 在另一個分頁中,在第三方 OAuth 用戶端應用程式上註冊回呼網址。
- 在「Auth provider credentials」(驗證供應商憑證) 部分,輸入下列資訊:
- 用戶端 ID
- 用戶端密鑰
- 權杖網址
- 授權網址
- 「Default continue URI」(預設接續 URI):選填。輸入預設重新導向 URI,在執行階段未提供接續 URI 時,將使用者重新導向至該位置。
- 按一下「Add provider config」。
新建立的驗證供應商會顯示在「Auth Providers」(驗證供應商) 清單中。
gcloud CLI
-
設定 OAuth 用戶端應用程式,註冊用戶端並取得用戶端 ID 和用戶端密鑰。使用該區段中的範本指定重新導向 URI。
-
使用用戶端憑證建立驗證提供者:
gcloud alpha agent-identity connectors 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" - 確認驗證提供者顯示在清單中,且狀態為
ENABLED:gcloud alpha agent-identity connectors list \ --project="
PROJECT_ID" \ --location="LOCATION" -
授予存取權限,允許代理和本機開發環境從驗證提供者擷取憑證。如要允許已部署的代理和個人使用者帳戶存取驗證提供者,請在驗證提供者資源上授予連接器使用者 (
roles/iamconnectors.user) 角色:-
授予已部署代理的 SPIFFE ID (代理身分) 存取權:
gcloud alpha agent-identity connectors add-iam-policy-binding
AUTH_PROVIDER_NAME\ --project="PROJECT_ID" \ --location="LOCATION" \ --role="roles/iamconnectors.user" \ --member="principal://agents.global.org-ORGANIZATION_ID.system.id.goog/resources/aiplatform/projects/PROJECT_NUMBER/locations/LOCATION/reasoningEngines/ENGINE_ID" -
授予個人使用者帳戶存取權,以便在本機開發及測試 (
adk web):gcloud alpha agent-identity connectors add-iam-policy-binding
AUTH_PROVIDER_NAME\ --project="PROJECT_ID" \ --location="LOCATION" \ --role="roles/iamconnectors.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:個人使用者帳戶的電子郵件地址。
設定 OAuth 用戶端應用程式
註冊 OAuth 用戶端憑證前,請先向第三方授權伺服器 (例如 Google、GitHub 或 Jira) 取得用戶端 ID 和用戶端密鑰。
如果您要連線至Google Cloud以外的第三方服務,請從該服務的開發人員入口網站取得 OAuth 用戶端憑證,並略過本節步驟。
註冊重新導向 URI
設定 OAuth 用戶端憑證時,您必須註冊驗證服務供應商的專屬回呼重新導向 URI。
使用下列範本建構重新導向 URI:
https://iamconnectorcredentials.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/connectors/CONNECTOR_NAME/oauthcallback更改下列內容:
PROJECT_ID: Google Cloud 專案 ID。LOCATION: The region where your auth provider will be deployed (for example,us-west1`)。CONNECTOR_NAME:驗證提供者的名稱。
例如:
https://iamconnectorcredentials.googleapis.com/v1/projects/my-project/locations/us-west1/connectors/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。
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 the Google Cloud Auth Provider so the CredentialManager can use it. CredentialManager.register_auth_provider(GcpAuthProvider()) # The URI to redirect the user to after consent is granted and the # callback is received by the auth provider. CONTINUE_URI = "https://YOUR_FRONTEND_URL/validateUserId" # Create the Auth Provider scheme using the auth provider's full resource name. auth_scheme = GcpAuthProviderScheme( name="projects/PROJECT_ID/locations/LOCATION/connectors/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 = LlmAgent( name="AGENT_NAME", model="gemini-2.5-flash", instruction="AGENT_INSTRUCTIONS", tools=[toolset], )
範例:連線至 BigQuery MCP
以下範例顯示 agent.py 設定,使用 3-legged OAuth 將代理連至 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 for Agent Identity Credentials service CredentialManager.register_auth_provider(GcpAuthProvider()) # The URI to redirect the user to after consent is granted and the callback is received. CONTINUE_URI = "http://127.0.0.1:8501/validateUserId" bigquery_mcp_auth_scheme = GcpAuthProviderScheme( name=f"projects/{project_id}/locations/LOCATION/connectors/{bigquery_mcp_auth_provider_id}", 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.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()) # 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/connectors/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 = 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)
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()) # The URI to redirect the user to after consent is completed. CONTINUE_URI="WEB_APP_VALIDATE_USER_URI" # Create Google Cloud auth provider by providing auth provider full resource name auth_scheme = GcpAuthProviderScheme( name="projects/PROJECT_ID/locations/LOCATION/connectors/AUTH_PROVIDER_NAME", continue_uri=CONTINUE_URI ) # 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], )
直接呼叫 API
如果未使用 ADK,代理必須呼叫 iamconnectorcredentials.retrieveCredentials API 才能取得權杖。
由於這是多步驟 OAuth 流程,API 會傳回長時間執行的作業 (LRO)。代理必須處理作業的生命週期:
- 初始要求:代理呼叫
retrieveCredentials。 - 需要同意聲明規定:如果使用者尚未同意,API 會傳回 LRO,其中中繼資料包含
auth_uri和consent_nonce。 - 前端重新導向:應用程式必須將使用者重新導向至
auth_uri。 - 完成:使用者授予同意聲明後,請使用
consent_nonce呼叫FinalizeCredential,完成流程並取得權杖。
更新用戶端應用程式
如要處理 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://iamconnectorcredentials.googleapis.com/v1alpha" 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。
如要部署至 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]"
],
},
)