次の方法で共有


.NET を使用してエージェントからカスタム API を呼び出す

エージェントからカスタム API を呼び出すには、複数の方法があります。 シナリオに応じて、 IDownstreamApiMicrosoftIdentityMessageHandler、または IAuthorizationHeaderProviderのいずれかを使用できます。 このガイドでは、独自の保護された API を呼び出すためのさまざまな方法について、3 つの方法すべてについて説明します。

エージェントから API を呼び出すには、エージェントが API に対して自身を認証するために使用できるアクセス トークンを取得する必要があります。 Microsoft.Identity.Web SDK for .NET を使用して Web API を呼び出することをお勧めします。 この SDK は、トークンの取得と検証のプロセスを簡略化します。 他の言語の場合は、 エージェント ID に Microsoft Entra エージェント SDK を使用します。

[前提条件]

  • ターゲット API を呼び出す適切なアクセス許可を持つエージェント ID。 代理操作のフローにはユーザーが必要です。
  • ターゲット API を呼び出す適切なアクセス許可を持つエージェント ユーザー。

シナリオに基づいて使用する方法を決定する

次の表は、使用する方法を決定するのに役立ちます。 ほとんどのシナリオでは、 IDownstreamApiを使用することをお勧めします。

方法 複雑さ 柔軟性 使用事例
IDownstreamApi Low ミディアム 構成による標準 REST API
MicrosoftIdentityMessageHandler ミディアム High 直接挿入 (DI) と構成可能なパイプラインを使用した HttpClient
IAuthorizationHeaderProvider High 非常に高 HTTP 要求を完全に制御する

IDownstreamApi は、3 つのオプションの中から保護された API を呼び出す推奨される方法です。 これは高度に構成可能であり、最小限のコード変更が必要です。 また、トークンの自動取得も提供します。

次の項目が必要な場合は、 IDownstreamApi を使用します。

  • 標準 REST API を呼び出している
  • 構成主導型のアプローチが必要です
  • 自動シリアル化/逆シリアル化が必要です
  • 最小限のコードを記述する

API を呼び出す

何が適切かを判断したら、カスタム Web API の呼び出しに進みます。

Warnung

セキュリティ リスクのために、エージェント ID ブループリントの運用環境では、クライアント シークレットをクライアント資格情報として使用しないでください。 代わりに、マネージド ID またはクライアント証明書を使用 するフェデレーション ID 資格情報 (FIC) などのより安全な認証方法を使用してください。 これらの方法により、アプリケーション構成内に機密性の高いシークレットを直接格納する必要がなくなり、セキュリティが強化されます。

  1. 必要な NuGet パッケージをインストールします。

    dotnet add package Microsoft.Identity.Web.DownstreamApi
    dotnet add package Microsoft.Identity.Web.AgentIdentities
    
  2. appsettings.jsonでトークン資格情報オプションと API を構成します。

    {
      "AzureAd": {
        "Instance": "https://login.microsoftonline.com/",
        "TenantId": "your-tenant-id",
        "ClientId": "your-blueprint-id",
        "ClientCredentials": [
          {
            "SourceType": "ClientSecret",
            "ClientSecret": "your-client-secret"
          }
        ]
      },
      "DownstreamApis": {
        "MyApi": {
          "BaseUrl": "https://api.example.com",
          "Scopes": ["api://my-api-client-id/read", "api://my-api-client-id/write"],
          "RelativePath": "/api/v1",
          "RequestAppToken": false
        }
      }
    }
    
  3. ダウンストリーム API サポートを追加するようにサービスを構成します。

    using Microsoft.Identity.Web;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add authentication
    builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
        .EnableTokenAcquisitionToCallDownstreamApi()
        .AddInMemoryTokenCaches();
    
    // Register downstream APIs
    builder.Services.AddDownstreamApis(
        builder.Configuration.GetSection("DownstreamApis"));
    
    // Add Agent Identities support
    builder.Services.AddAgentIdentities();
    
    builder.Services.AddControllersWithViews();
    
    var app = builder.Build();
    app.UseAuthentication();
    app.UseAuthorization();
    app.MapControllers();
    app.Run();
    
  4. IDownstreamApiを使用して保護された API を呼び出します。 API を呼び出すときは、 WithAgentIdentity または WithAgentUserIdentity メソッドを使用して、エージェント ID またはエージェント ユーザー ID を指定できます。 IDownstreamApi は、トークンの取得を自動的に処理し、アクセス トークンを要求にアタッチします。

    • WithAgentIdentityの場合は、アプリ専用トークン (自律エージェント) を使用して API を呼び出すか、ユーザーの代わりに (対話型エージェント) API を呼び出します。

      using Microsoft.Identity.Abstractions;
      using Microsoft.AspNetCore.Authorization;
      using Microsoft.AspNetCore.Mvc;
      
      [Authorize]
      public class ProductsController : Controller
      {
          private readonly IDownstreamApi _api;
      
          public ProductsController(IDownstreamApi api)
          {
              _api = api;
          }
      
          // GET request for app only token scenario for agent identity
          public async Task<IActionResult> Index()
          {
      
              string agentIdentity = "<your-agent-identity>";
              var products = await _api.GetForAppAsync<List<Product>>(
                  "MyApi",
                  "products",
                  options => options.WithAgentIdentity(agentIdentity));
      
              return View(products);
          }
      
          // GET request for on-behalf of user token scenario for agent identity
          public async Task<IActionResult> UserProducts()
          {
      
              string agentIdentity = "<your-agent-identity>";
              var products = await _api.GetForUserAsync<List<Product>>(
                  "MyApi",
                  "products",
                  options => options.WithAgentIdentity(agentIdentity));
      
              return View(products);
          }
      }
      
    • WithAgentUserIdentityでは、エージェント ユーザーを識別するために、ユーザー プリンシパル名 (UPN) またはオブジェクト ID (OID) を指定できます。

      using Microsoft.Identity.Abstractions;
      using Microsoft.AspNetCore.Authorization;
      using Microsoft.AspNetCore.Mvc;
      
      [Authorize]
      public class ProductsController : Controller
      {
          private readonly IDownstreamApi _api;
      
          public ProductsController(IDownstreamApi api)
          {
              _api = api;
          }
      
          // GET request for agent user identity using UPN
          public async Task<IActionResult> Index()
          {
      
              string agentIdentity = "<your-agent-identity>";
              string userUpn = "user@contoso.com";
      
              var products = await _api.GetForUserAsync<List<Product>>(
                  "MyApi",
                  "products",
                  options => options.WithAgentUserIdentity(agentIdentity, userUpn));
              return View(products);
          }
      
          // GET request for agent user identity using OID
          public async Task<IActionResult> UserProducts()
          {
      
              string agentIdentity = "<your-agent-identity>";
              string userOid = "user-object-id";
      
              var products = await _api.GetForUserAsync<List<Product>>(
                  "MyApi",
                  "products",
                  options => options.WithAgentUserIdentity(agentIdentity, userOid));
      
              return View(products);
          }
      
      }