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

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

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

תהליך עבודה של OAuth תלת-רגלי (‎3-legged OAuth‏)

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

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

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

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

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

    כדי להפעיל ממשקי API, צריך את ההרשאה serviceusage.services.enable. אם יצרתם את הפרויקט, סביר להניח שכבר יש לכם את ההרשאה הזו דרך התפקיד "בעלים" (roles/owner). אחרת, תוכלו לקבל את ההרשאה הזו דרך התפקיד "אדמין בממשק 'שימוש בשירות'" (roles/serviceusage.serviceUsageAdmin). איך מקצים תפקידים

    להפעלת ה-API

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

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

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

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

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

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

כדי ליצור ספק אימות תלת-שלבי ולהשתמש בו, נדרשות ההרשאות הבאות:

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

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

יצירת ספק אימות תלת-שלבי (3-legged)

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

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

המסוף

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

    כניסה ל-Agent Registry

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

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

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

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

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

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

‫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 של הסוכן שנפרס (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"
    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 consent screen

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

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

        עוברים אל APIs & Services >OAuth consent screen >Clients

      2. לוחצים על Create credentials >OAuth client ID.
      3. בוחרים באפשרות אפליקציית אינטרנט מהרשימה.
      4. מזינים שם קליט ללקוח ה-OAuth.
      5. בקטע Authorized redirect URIs, לוחצים על Add 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 שמחברת נציג לשרת 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). הנציג צריך לטפל במחזור החיים של הפעולה:

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

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

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

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

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

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

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