כדי לתת לסוכן גישה לכלים ולשירותים חיצוניים (כמו משימות ב-Jira או מאגרים ב-GitHub) בשם משתמש קצה ספציפי, צריך להגדיר ספק אימות OAuth תלת-רגלי במנהל האימות של Agent Identity.
ספקי אימות OAuth תלת-רגלי מנהלים בשבילכם את ההפניה האוטומטית של המשתמשים ואת הטוקנים. כך לא צריך לכתוב קוד מותאם אישית כדי לטפל בהרשאה באמצעות OAuth 2.0.
תהליך עבודה של OAuth תלת-רגלי (3-legged OAuth)
ספקי אימות OAuth עם 3 רגליים דורשים הסכמה מהמשתמש כי הנציג ניגש למשאבים בשם המשתמש.
- הודעה והפניה אוטומטית: ממשק הצ'אט מבקש מהמשתמש להיכנס לחשבון ואז מפנה אותו לדף ההסכמה של אפליקציית הצד השלישי.
- הסכמה ואחסון: אחרי שהמשתמש נותן הרשאה, מנהל האימות של Agent Identity שומר את אסימוני ה-OAuth שנוצרו במאגר פרטי כניסה שמנוהל על ידי Google.
- הזרקה: כשמשתמשים בערכה לפיתוח סוכנים (ADK), הסוכן מאחזר באופן אוטומטי את האסימון מספק האימות ומזריק אותו לכותרות של הפעלת הכלי.
לפני שמתחילים
- מוודאים שבחרתם בשיטת האימות הנכונה.
-
מפעילים את Agent Identity Connector API, אם הוא עדיין לא מופעל.
התפקידים שנדרשים כדי להפעיל ממשקי API
כדי להפעיל ממשקי API, צריך את ההרשאה
serviceusage.services.enable. אם יצרתם את הפרויקט, סביר להניח שכבר יש לכם את ההרשאה הזו דרך התפקיד "בעלים" (roles/owner). אחרת, תוכלו לקבל את ההרשאה הזו דרך התפקיד "אדמין בממשק 'שימוש בשירות'" (roles/serviceusage.serviceUsageAdmin). איך מקצים תפקידים - יוצרים ופורסים נציג.
- מוודאים שיש לכם אפליקציית ממשק משתמש (frontend) לטיפול בהנחיות לכניסת משתמשים ובהפניה אוטומטית לדפי הסכמה של צד שלישי.
- מוודאים שיש לכם את התפקידים הנדרשים כדי להשלים את המשימה.
התפקידים הנדרשים
כדי לקבל את ההרשאות שדרושות ליצירה ולשימוש בספק אימות ב-3 שלבים, צריך לבקש מהאדמין להקצות לכם את התפקידים הבאים ב-IAM בפרויקט:
-
כדי ליצור ספקי אימות:
- אדמין של מחבר IAM (
roles/iamconnectors.admin) - עריכת מחברים ב-IAM (
roles/iamconnectors.editor)
- אדמין של מחבר IAM (
-
כדי להשתמש בספקי אימות:
- משתמש במחבר IAM (
roles/iamconnectors.user) - Service Usage Consumer (
roles/serviceusage.serviceUsageConsumer)
- משתמש במחבר IAM (
להסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.
התפקידים המוגדרים מראש האלה כוללים את ההרשאות שנדרשות כדי ליצור ספק אימות תלת-שלבי ולהשתמש בו. כדי לראות בדיוק אילו הרשאות נדרשות, אפשר להרחיב את הקטע ההרשאות הנדרשות:
ההרשאות הנדרשות
כדי ליצור ספק אימות תלת-שלבי ולהשתמש בו, נדרשות ההרשאות הבאות:
-
כדי ליצור ספקי אימות:
iamconnectors.connectors.create -
כדי להשתמש בספקי אימות:
-
iamconnectors.connectors.retrieveCredentials -
aiplatform.endpoints.predict -
aiplatform.sessions.create
-
יכול להיות שתקבלו את ההרשאות האלה באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש אחרים.
יצירת ספק אימות תלת-שלבי (3-legged)
כדי להגדיר את הפרטים ופרטי הכניסה של אפליקציות צד שלישי, צריך ליצור ספק אימות.
כדי ליצור ספק אימות תלת-שלבי, משתמשים במסוף Google Cloud או ב-Google Cloud CLI.
המסוף
- נכנסים לדף Agent Registry במסוף Google Cloud .
- לוחצים על שם הנציג שרוצים ליצור לו ספק אימות.
- לוחצים על זהות.
- בקטע Auth Providers, לוחצים על Add auth provider.
-
בחלונית Add auth provider, מזינים שם ותיאור.
השם יכול לכלול רק אותיות קטנות, מספרים או מקפים, הוא לא יכול להסתיים במקף והוא חייב להתחיל באות קטנה.
- ברשימה OAuth Type, בוחרים באפשרות OAuth (3 legged).
- לוחצים על Create and continue.
- כדי לתת לזהות של הסוכן הרשאה להשתמש בספק האימות, לוחצים על מתן גישה.
הפעולה הזו מקצה באופן אוטומטי את התפקיד Connector User (
roles/iamconnectors.user) לזהות הסוכן במשאב של ספק האימות. - מעתיקים את כתובת ה-URL להתקשרות חזרה.
- בכרטיסייה נפרדת, רושמים את כתובת ה-URL להחזרה (callback) באפליקציית לקוח OAuth של הצד השלישי.
- בקטע Auth provider credentials, מזינים את הפרטים הבאים:
- מזהה לקוח
- סוד לקוח
- כתובת URL לטוקן
- כתובת URL להרשאה
- Default continue URI: אופציונלי. מזינים את כתובת ה-URI של ההפניה האוטומטית כברירת מחדל, שאליה המשתמשים יופנו אחרי שהם יתנו את ההסכמה שלהם, אם לא צוינה כתובת URI להמשך בזמן הריצה.
- לוחצים על Add provider config.
ספק האימות החדש שנוצר מופיע ברשימה Auth Providers.
CLI של gcloud
-
מגדירים את אפליקציית הלקוח ב-OAuth כדי לרשום את הלקוח ולקבל מזהה לקוח וסוד לקוח. מציינים את ה-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" -
נותנים הרשאות גישה כדי לאפשר לסוכן ולסביבת הפיתוח המקומית לאחזר את פרטי הכניסה מספק האימות. כדי לאפשר לנציג שנפרס ולחשבון המשתמש האישי שלכם לגשת לספק האימות, מקצים את התפקיד Connector User (
roles/iamconnectors.user) במשאב של ספק האימות:-
נותנים גישה למזהה ה-SPIFFE של הסוכן שנפרס (Agent Identity):
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 . -
LOCATION: המיקום שבו נפרסו ספק האימות והנציג (לדוגמה,us-west1). -
AUTH_PROVIDER_NAME: השם של ספק האימות (לדוגמה,bigquery-mcp-3lo-authprovider). -
AUTHORIZATION_URL: כתובת ה-URL של שרת ההרשאות (לדוגמה,https://accounts.google.com/o/oauth2/v2/auth). -
TOKEN_URL: כתובת ה-URL של שרת האסימונים (לדוגמה,https://oauth2.googleapis.com/token). CLIENT_ID: מזהה הלקוח ב-OAuth שיצרתם בשירות של הצד השלישי.CLIENT_SECRET: סוד הלקוח של OAuth שיצרתם בשירות של הצד השלישי.-
ORGANIZATION_ID: מזהה הארגון ב- Google Cloud . -
PROJECT_NUMBER: מספר הפרויקט ב- Google Cloud . -
ENGINE_ID: המזהה של סוכן מנוע החשיבה הרציונלית שנפרס. -
USER_EMAIL: כתובת האימייל של חשבון המשתמש האישי שלכם.
הגדרת אפליקציית הלקוח של OAuth
לפני שאתם רושמים את פרטי הכניסה של לקוח OAuth, אתם צריכים לקבל מזהה לקוח וסוד לקוח משרת ההרשאות של הצד השלישי (לדוגמה, Google, GitHub או Jira).
אם אתם מתחברים לשירות של צד שלישי מחוץ ל-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 . 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), אתם יכולים להגדיר את מסך ההסכמה וליצור פרטי כניסה של לקוח OAuth במסוף Google Cloud :
-
הגדרת מסך ההסכמה של OAuth:
- במסוף Google Cloud , נכנסים לדף APIs & Services >מסך הסכמה של OAuth.
- בקטע App information, מזינים שם לאפליקציה (למשל BigQuery Manager Application) וכתובת אימייל לתמיכה.
- בקטע Audience, בוחרים באפשרות Internal או External.
- מזינים את הפרטים ליצירת קשר כדי לקבל התראות.
- קוראים ומאשרים את המדיניות של Google בנושא נתוני משתמשים בשירותי API.
- לוחצים על סיום.
-
יוצרים את פרטי הכניסה של לקוח OAuth:
- במסוף Google Cloud , נכנסים לדף APIs & Services >OAuth consent screen >Clients.
- לוחצים על Create credentials >OAuth client ID.
- בוחרים באפשרות אפליקציית אינטרנט מהרשימה.
- מזינים שם קליט ללקוח ה-OAuth.
- בקטע Authorized redirect URIs, לוחצים על Add URI ומזינים את ה-URI של ההפניה האוטומטית שיצרתם.
- לוחצים על יצירה. בתיבת הדו-שיח OAuth client created, מעתיקים את הערכים שנוצרו בשדות Client ID ו-Client Secret.
-
אימות בקוד של הנציג
כדי לאמת את הסוכן, אתם יכולים להשתמש ב-ADK או לשלוח קריאה ישירות ל-Agent Identity API.
ADK
מפנים לספק האימות בקוד של הנציג באמצעות ערכת הכלים של MCP ב-ADK.
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 שמחברת נציג לשרת MCP של BigQuery באמצעות OAuth עם 3 רגליים:
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
מפנים לספק האימות בקוד של הסוכן באמצעות ערכת הכלים של Agent Registry MCP ב-ADK.
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, הנציג צריך לשלוח קריאה ל-API של iamconnectorcredentials.retrieveCredentials כדי לקבל את הטוקן.
מכיוון שמדובר בתהליך OAuth עם כמה שלבים, ה-API מחזיר פעולה ממושכת (LRO). הנציג צריך לטפל במחזור החיים של הפעולה:
- בקשה ראשונית: הסוכן מתקשר אל
retrieveCredentials. - נדרשת הסכמה: אם המשתמש לא נתן הסכמה, ה-API מחזיר LRO שבו המטא-נתונים מכילים את
auth_uriו-consent_nonce. - הפניה אוטומטית של ממשק קצה (frontend): האפליקציה צריכה להפנות את המשתמש אל
auth_uri. - השלמה: אחרי שהמשתמש נותן הסכמה, מפעילים את
FinalizeCredentialבאמצעותconsent_nonceכדי להשלים את התהליך ולקבל את האסימון.
עדכון האפליקציה בצד הלקוח
כדי לטפל בכניסה של משתמשים ובהפניה אוטומטית ל-OAuth עם 3 רגליים, האפליקציה בצד הלקוח צריכה לבצע את השלבים הבאים כדי לנהל את הסכמת המשתמשים ולהמשיך את השיחה:
שרת ממשק משתמש לדוגמה
אתם יכולים להוריד ולהריץ שרת ממשק משתמש לדוגמה שמשתמש ב-uvicorn. לפני שמתחילים, ודאו שיש לכם חשבון ב-GitHub ושהתקנתם את pip.
כדי להגדיר ולהפעיל את שרת ממשק המשתמש לדוגמה:
-
משכפלים את המאגר של
adk-pythonב-GitHub:git clone https://github.com/google/adk-python.git
-
עוברים למאגר ומפעילים סביבה וירטואלית של Python:
cd adk-python python3 -m venv .venv source .venv/bin/activate
-
עוברים לספריית הלקוח של ממשק המשתמש לדוגמה:
cd contributing/samples/integrations/gcp_auth/client
-
מתקינים את יחסי התלות של הלקוח:
pip install -r requirements.txt
-
לפני שמפעילים את השרת, מגדירים את משתנה הסביבה
AGENT_PROJECT_DIRכדי לציין את הספרייה שבה נמצא קוד הנציג. אחרת, האפליקציה מחפשת סוכנים בתיקיית ההורה של ספריית הלקוח כברירת מחדל.מפעילים את שרת ממשק המשתמש לדוגמה באמצעות
uvicorn. מוודאים שהיציאה תואמת ל-URI להפניה אוטומטית שהוגדר בלקוח OAuth:export AGENT_PROJECT_DIR="/path/to/your/agent_project" uvicorn main:app --port 8501 --reload
-
פותחים את
http://localhost:8501בדפדפן. (הערה: צריך להשתמש ב-localhostולא ב-127.0.0.1, כי כתובת ה-URL להפניה אוטומטית של OAuth דורשת באופן ספציפי את שם המארחlocalhost). מגדירים את ההגדרות, לוחצים על Save & Apply Settings ומתקשרים עם הנציג.
אפליקציה עם ממשק משתמש בהתאמה אישית
כדי להטמיע את היכולות האלה ישירות באפליקציה עם ממשק משתמש בהתאמה אישית, מבצעים את הפעולות הבאות:
טיפול בטריגר של ההרשאה
כשהסוכן צריך הסכמה מהמשתמש, הוא מחזיר בקשה להפעלת פונקציה 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
הטמעה של נקודת קצה לאימות משתמשים
מטמיעים נקודת קצה לאימות בשרת האינטרנט (אותו URI שצוין בתור continue_uri במהלך ההגדרה). נקודת הקצה הזו צריכה לבצע את הפעולות הבאות:
- מקבלים את
user_id_validation_state,auth_provider_nameו-uuidכפרמטרים של שאילתה. - מאחזרים את הערכים של
user_idו-consent_nonceמאחסון הסשן. אם כמה תהליכי הרשאה פועלים בו-זמנית, צריך להשתמש ב-uuidכדי להתאים לסשן הנכון. - שולחים קריאה ל-API של
FinalizeCredentialsשל ספק האימות עם הפרמטרים האלה. - סוגרים את חלון ההרשאה אחרי שמקבלים תשובה שהפעולה בוצעה בהצלחה.
דוגמה: נקודת קצה לאימות של FastAPI (main.py)
הדוגמה הבאה מראה נקודת קצה מלאה לאימות ב-FastAPI שמטפלת בקריאה החוזרת (callback) של 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 מופעל.
אם אתם פורסים ב-Agent Runtime ב-Gemini Enterprise Agent Platform, השתמשו בדגל 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]"
],
},
)