אימות באמצעות OAuth תלת-רגלי עם מנהל ההרשאות

כדי להעניק לסוכן גישה לכלים ולשירותים חיצוניים (כמו משימות ב-Jira או מאגרי GitHub) בשם משתמש קצה ספציפי, צריך להגדיר ספק אימות OAuth תלת-רגלי במנהל האימות של זהות הסוכן.

ספקי אימות מסוג OAuth תלת-רגלי מנהלים בשבילכם את ההפניה מחדש של המשתמשים ואת הטוקנים. כך לא צריך לכתוב קוד מותאם אישית כדי לטפל בתהליכי OAuth 2.0 מורכבים.

תהליך עבודה של OAuth תלת-רגלי

ספקי אימות OAuth 3.0 דורשים הסכמה מהמשתמש כי הסוכן ניגש למשאבים בשם המשתמש.

  1. בקשה להרשמה והפניה אוטומטית: ממשק הצ'אט מבקש מהמשתמש להיכנס לחשבון ואז מפנה אותו לדף ההסכמה של אפליקציית הצד השלישי.
  2. הסכמה ואחסון: אחרי שהמשתמש מעניק הרשאה, מנהל האימות של Agent Identity מאחסן את אסימוני ה-OAuth שנוצרו בכספת פרטי הכניסה שמנוהלת על ידי Google.
  3. החדרה: כשמשתמשים בערכה לפיתוח סוכנים (ADK), הסוכן מאחזר באופן אוטומטי את האסימון מספק האימות ומחדיר אותו לכותרות של הפעלת הכלי.

לפני שמתחילים

  1. מוודאים שבחרתם את שיטת האימות הנכונה.
  2. מפעילים את Agent Identity Connector API.

    תפקידים שנדרשים להפעלת ממשקי API

    כדי להפעיל ממשקי API, צריך את תפקיד ה-IAM 'אדמין של Service Usage' (roles/serviceusage.serviceUsageAdmin), שכולל את ההרשאה serviceusage.services.enable. איך מקצים תפקידים

    להפעלת ה-API

  3. יצירה ופריסה של סוכן.
  4. צריך לוודא שיש לכם אפליקציית frontend לטיפול בהנחיות לכניסה של משתמשים ולהפניה לדפי הסכמה של צד שלישי.
  5. מוודאים שיש לכם את התפקידים הנדרשים כדי להשלים את המשימה הזו.

התפקידים הנדרשים

כדי לקבל את ההרשאות שדרושות ליצירה ולשימוש בספק אימות עם 3 רגליים, צריך לבקש מהאדמין להקצות לכם את תפקידי ה-IAM הבאים בפרויקט:

להסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

התפקידים המוגדרים מראש כוללים את ההרשאות שנדרשות ליצירה ולשימוש בספק אימות עם 3 רגליים. כדי לראות בדיוק אילו הרשאות נדרשות, אפשר להרחיב את הקטע ההרשאות הנדרשות:

ההרשאות הנדרשות

כדי ליצור ספק אימות עם 3 רגליים ולהשתמש בו, צריך את ההרשאות הבאות:

  • כדי ליצור ספקי אימות: iamconnectors.connectors.create
  • כדי להשתמש בספקי אימות:
    • iamconnectors.connectors.retrieveCredentials
    • aiplatform.endpoints.predict
    • aiplatform.sessions.create

יכול להיות שתקבלו את ההרשאות האלה באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש אחרים.

יצירת ספק אימות עם 3 רגליים

יוצרים ספק אימות כדי להגדיר את ההגדרות ופרטי הכניסה של אפליקציות צד שלישי.

כדי ליצור ספק אימות עם 3 רגליים, משתמשים במסוף Google Cloud או ב-Google Cloud CLI.

המסוף

  1. נכנסים לדף Agent Registry במסוף Google Cloud .

    כניסה ל-Agent Registry

  2. לוחצים על השם של הסוכן שרוצים ליצור עבורו ספק אימות.
  3. לוחצים על זהות.
  4. בקטע Auth Providers (ספקי אימות), לוחצים על Add auth provider (הוספת ספק אימות).
  5. בחלונית הוספת ספק אימות, מזינים שם ותיאור.

    השם יכול להכיל רק אותיות קטנות, מספרים או מקפים, הוא לא יכול להסתיים במקף והוא חייב להתחיל באות קטנה.

  6. מהרשימה סוג OAuth בוחרים באפשרות OAuth (תלת-רגלי) .
  7. לוחצים על Create and continue.
  8. כדי לתת לסוכן הרשאה להשתמש בספק האימות, לוחצים על Grant access (מתן גישה).

    הפעולה הזו מקצה אוטומטית את התפקיד Connector User (roles/iamconnectors.user) לזהות הסוכן במשאב ספק האימות.

  9. מעתיקים את כתובת ה-URL להתקשרות חזרה.
  10. בכרטיסייה נפרדת, רושמים את כתובת ה-URL של הקריאה החוזרת באפליקציית לקוח OAuth של הצד השלישי.
  11. בקטע Auth provider credentials (פרטי כניסה של ספק אימות), מזינים את הפרטים הבאים:
    • Client ID
    • סוד לקוח
    • כתובת URL לטוקן
    • כתובת URL של הרשאה
  12. לוחצים על Add provider config (הוספת הגדרת ספק).

ספק האימות החדש שנוצר מופיע ברשימה ספקי אימות.

‫CLI של gcloud

  1. מגדירים את אפליקציית לקוח ה-OAuth כדי לרשום את הלקוח ולקבל מזהה לקוח וסוד לקוח. מציינים את ה-URI של ההפניה באמצעות התבנית בקטע הזה.

  2. יוצרים את ספק האימות באמצעות פרטי הכניסה של הלקוח:

    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"
  3. מוודאים שספק האימות מופיע ברשימה והסטטוס שלו הוא ENABLED:
    gcloud alpha agent-identity connectors list \
       --project="PROJECT_ID" \
       --location="LOCATION"
  4. צריך להעניק הרשאות גישה כדי לאפשר לסוכן ולסביבת הפיתוח המקומית לאחזר פרטי כניסה מספק האימות. כדי לאפשר לסוכן הפרוס ולחשבון המשתמש האישי שלכם לגשת לספק האימות, צריך להקצות את התפקיד Connector User (roles/iamconnectors.user) במשאב של ספק האימות:

    1. נותנים גישה למזהה SPIFFE של הסוכן שפרסתם (זהות הסוכן):

      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"
    2. הענקת גישה לחשבון המשתמש האישי שלך לצורך פיתוח ובדיקה מקומיים (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 הייעודית להפניה אוטומטית של ספק האימות.

  1. יוצרים את ה-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

  2. אם אתם מתחברים ל Google Cloud שירותים (כמו BigQuery), אתם יכולים להגדיר את מסך ההסכמה וליצור פרטי כניסה של לקוח OAuth במסוף Google Cloud :

    1. הגדרת מסך ההסכמה ל-OAuth:

      1. במסוף Google Cloud , נכנסים לדף APIs & Services >מסך הסכמה של OAuth.

        עוברים אל APIs & Services >מסך ההסכמה של OAuth

      2. בקטע App information, מזינים שם לאפליקציה (למשל BigQuery Manager Application) וכתובת אימייל לתמיכה.
      3. בקטע קהל, בוחרים באפשרות פנימי או חיצוני.
      4. מזינים את הפרטים ליצירת קשר כדי לקבל התראות.
      5. קוראים ומאשרים את המדיניות של Google בנושא נתוני משתמשים בשירותי API.
      6. לוחצים על סיום.
    2. יוצרים את פרטי הכניסה של לקוח OAuth:

      1. במסוף Google Cloud , נכנסים לדף APIs & Services >OAuth consent screen >Clients.

        עוברים אל APIs & Services >מסך ההסכמה של OAuth >לקוחות

      2. לוחצים על Create credentials >OAuth client ID (יצירת פרטי כניסה >מזהה לקוח OAuth).
      3. בוחרים באפשרות Web application (אפליקציית אינטרנט) מהרשימה.
      4. מזינים שם שקל לזכור ללקוח ה-OAuth.
      5. בקטע Authorized redirect URIs (כתובות URI מורשות להפניה אוטומטית), לוחצים על Add URI (הוספת URI) ומזינים את כתובת ה-URI להפניה אוטומטית שיצרתם.
      6. לוחצים על יצירה. בתיבת הדו-שיח 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 שמקשרת סוכן לשרת BigQuery MCP באמצעות 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, הנציג שלכם צריך לשלוח קריאה ל-iamconnectorcredentials.retrieveCredentials API כדי לקבל את הטוקן.

מכיוון שמדובר בתהליך OAuth רב-שלבי, ה-API מחזיר פעולה ממושכת (LRO). הסוכן צריך לטפל במחזור החיים של הפעולה:

  1. הבקשה הראשונית: הסוכן מתקשר אל retrieveCredentials.
  2. נדרשת הסכמה: אם המשתמש לא העניק הסכמה, ה-API מחזיר LRO שבו המטא-נתונים מכילים את הערך auth_uri ואת הערך consent_nonce.
  3. הפניה אוטומטית בחזית האתר: האפליקציה צריכה להפנות את המשתמש אל auth_uri.
  4. השלמה: אחרי שהמשתמש מביע הסכמה, מפעילים את FinalizeCredential באמצעות consent_nonce כדי להשלים את התהליך ולקבל את האסימון.

עדכון האפליקציה בצד הלקוח

כדי לטפל בכניסה של משתמשים ובהפניה אוטומטית ב-OAuth 3.0, האפליקציה בצד הלקוח צריכה לבצע את השלבים הבאים כדי לנהל את הסכמת המשתמש ולחדש את השיחה:

שרת לדוגמה של ממשק משתמש

אפשר להוריד ולהריץ שרת ממשק משתמש לדוגמה שמשתמש ב-uvicorn. לפני שמתחילים, מוודאים שיש לכם חשבון ב-GitHub ושהתקנתם את pip.

כדי להגדיר ולהפעיל את שרת ממשק המשתמש לדוגמה:

  1. משכפלים את adk-python המאגר ב-GitHub:

    git clone https://github.com/google/adk-python.git
  2. מנווטים למאגר ומפעילים סביבה וירטואלית של Python:

    cd adk-python
    python3 -m venv .venv
    source .venv/bin/activate
  3. עוברים לספריית הלקוח של ממשק המשתמש לדוגמה:

    cd contributing/samples/integrations/gcp_auth/client
  4. מתקינים את יחסי התלות של הלקוח:

    pip install -r requirements.txt
  5. לפני שמפעילים את השרת, מגדירים את משתנה הסביבה AGENT_PROJECT_DIR כדי לציין את הספרייה שבה נמצא קוד הסוכן. אחרת, האפליקציה תחפש סוכנים כברירת מחדל בתיקיית האב של תיקיית הלקוח.

    מפעילים את שרת ממשק המשתמש לדוגמה באמצעות uvicorn. מוודאים שהיציאה תואמת לכתובת ה-URI להפניה אוטומטית שהוגדרה בלקוח OAuth:

    export AGENT_PROJECT_DIR="/path/to/your/agent_project"
    uvicorn main:app --port 8501 --reload
  6. פותחים את http://localhost:8501 בדפדפן. (הערה: חובה להשתמש ב-localhost ולא ב-127.0.0.1, כי כתובת ה-URL להפניה אוטומטית של OAuth מחייבת זאת). מציינים את ההגדרות, לוחצים על שמירת ההגדרות והחלתן, ואז מתקשרים עם הנציג.

אפליקציה עם ממשק משתמש מותאם אישית

כדי להטמיע את היכולות האלה ישירות באפליקציית ממשק משתמש בהתאמה אישית: פועלים לפי השלבים הבאים:

טיפול בהפעלת ההרשאה

כשסוכן צריך הסכמה מהמשתמש, הוא מחזיר קריאה לפונקציה adk_request_credential. האפליקציה שלכם צריכה ליירט את השיחה הזו כדי להפעיל תיבת דו-שיח של הרשאת משתמש או הפניה אוטומטית.

ניהול הקשר של הסשן על ידי תיעוד של consent_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 במהלך ההגדרה). נקודת הקצה הזו צריכה:

  1. מקבלים את הערכים user_id_validation_state ו-auth_provider_name כפרמטרים של שאילתה.
  2. מאחזרים את הערכים של user_id ושל consent_nonce מהקשר של הסשן.
  3. שולחים קריאה ל-API של ספק האימות עם הפרמטרים האלה.FinalizeCredentials
  4. סגירה של חלון ההרשאה אחרי קבלת תשובה על הצלחה.
דוגמה: נקודת קצה לאימות 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 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]"
        ],
    },
)

המאמרים הבאים