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

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

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

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

ספקי אימות OAuth עם 2 רגליים משתמשים בזהות של הסוכן ולא דורשים הסכמה מהמשתמש. ‫Google מנהלת את האחסון של פרטי הכניסה של הלקוח. כשמשתמשים בערכה לפיתוח סוכנים (ADK), המערכת מאחזרת באופן אוטומטי את אסימוני הגישה שנוצרו ומזריקה אותם לכותרות של הפעלת הכלי.

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

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

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

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

    להפעלת ה-API

  3. יצירה ופריסה של סוכן.

  4. מקבלים את מזהה הלקוח ואת סוד הלקוח מאפליקציית הצד השלישי שרוצים להתחבר אליה.

  5. מוודאים שיש לכם את התפקידים הנדרשים כדי להשלים את המשימה הזו.

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

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

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

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

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

כדי ליצור ספק אימות של זהות סוכן עם 2 רגליים ולהשתמש בו, נדרשות ההרשאות הבאות:

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

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

יצירת ספק אימות דו-רגלי

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

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

המסוף

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

    כניסה ל-Agent Registry

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

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

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

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

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

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

Google Cloud CLI

  1. יוצרים את ספק האימות:

    gcloud alpha agent-identity connectors create AUTH_PROVIDER_NAME \
        --location="LOCATION" \
        --two-legged-oauth-client-id="CLIENT_ID" \
        --two-legged-oauth-client-secret="CLIENT_SECRET" \
        --two-legged-oauth-token-endpoint="TOKEN_ENDPOINT"
  2. מוודאים שספק האימות מופיע ברשימה והסטטוס שלו הוא ENABLED:
    gcloud alpha agent-identity connectors list \
       --project="PROJECT_ID" \
       --location="LOCATION"
  3. צריך להעניק הרשאות גישה כדי לאפשר לסוכן ולסביבת הפיתוח המקומית לאחזר פרטי כניסה מספק האימות. כדי לאפשר לסוכן הפרוס ולחשבון המשתמש האישי שלכם לגשת לספק האימות, צריך להקצות את התפקיד 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: כתובת האימייל בחשבון המשתמש האישי שלכם.

אימות בקוד הסוכן

כדי לאמת את הנציג, אפשר להשתמש ב-ADK.

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())

# Create the Google Cloud Auth Provider scheme using the auth provider's full resource name.
auth_scheme = GcpAuthProviderScheme(
    name="projects/PROJECT_ID/locations/LOCATION/connectors/AUTH_PROVIDER_NAME"
)

# 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="YOUR_AGENT_NAME",
    model="gemini-2.0-flash",
    instruction="YOUR_AGENT_INSTRUCTIONS",
    tools=[toolset],
)

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())

# Create Auth Config
spotify_auth_config = AuthConfig(
    auth_scheme=GcpAuthProviderScheme(
        name="projects/PROJECT_ID/locations/LOCATION/connectors/AUTH_PROVIDER_NAME"
    )
)

# 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="YOUR_AGENT_NAME",
    model="YOUR_MODEL_NAME",
    instruction="YOUR_AGENT_INSTRUCTIONS",
    tools=[spotify_search_track_tool],
)

app = App(
    name="YOUR_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())

# Create Google Cloud auth provider scheme by providing Auth Provider full resource name
auth_scheme = GcpAuthProviderScheme(
    name="projects/PROJECT_ID/locations/LOCATION/connectors/AUTH_PROVIDER_NAME"
)

# 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="YOUR_AGENT_NAME",
    model="YOUR_MODEL_NAME",
    instruction="YOUR_AGENT_INSTRUCTIONS",
    tools=[toolset],
)

  

התקנת יחסי תלות לבדיקה מקומית

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

  1. יוצרים ומפעילים סביבה וירטואלית:
    python3 -m venv env
    source env/bin/activate
  2. מתקינים את החבילות הנדרשות:
    pip install google-cloud-aiplatform[agent_engines,adk] google-adk[agent-identity]

פריסת הסוכן

כשפורסים את הסוכן ב- Google Cloud, חשוב לוודא שאימות הזהות של הסוכן מופעל.

אם אתם פורסים ל-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]"],
    },
)

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