.NET 사용하여 에이전트에서 Microsoft Graph API 호출

이 문서에서는 에이전트 ID 또는 에이전트의 사용자 계정을 사용하여 에이전트에서 Microsoft Graph API 호출하는 방법을 설명합니다.

에이전트에서 API를 호출하려면 에이전트가 API에 자신을 인증하는 데 사용할 수 있는 액세스 토큰을 가져와야 합니다. Microsoft.Identity.Web SDK를 사용하는 것이 .NET의 웹 API를 호출하는 데 권장됩니다. 이 SDK는 토큰을 획득하고 유효성을 검사하는 프로세스를 간소화합니다. 다른 언어의 경우 Microsoft Entra ID Auth SDK(사이드카)를 사용합니다.

사전 요구 사항

  • 대상 API를 호출할 수 있는 적절한 권한이 있는 에이전트 ID입니다. 대신 흐름을 위한 사용자 계정이 필요합니다.
  • 대상 API를 호출할 수 있는 적절한 권한이 있는 에이전트의 사용자 계정입니다.

Microsoft Graph API 호출

  1. Microsoft.Identity.Web.GraphServiceClient를 설치하여 Graph SDK의 인증을 처리하고 Microsoft.Identity.Web.AgentIdentities 패키지를 사용하여 에이전트 ID에 대한 지원을 추가합니다.

    dotnet add package Microsoft.Identity.Web.GraphServiceClient
    dotnet add package Microsoft.Identity.Web.AgentIdentities
    
  2. 서비스 컬렉션에서 Microsoft Graph 및 에이전트 ID에 대한 지원을 추가합니다.

    using Microsoft.Identity.Web;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add authentication (web app or web API)
    builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
        .EnableTokenAcquisitionToCallDownstreamApi()
        .AddInMemoryTokenCaches();
    
    // Add Microsoft Graph support
    builder.Services.AddMicrosoftGraph();
    
    // Add Agent Identities support
    builder.Services.AddAgentIdentities();
    
    var app = builder.Build();
    app.UseAuthentication();
    app.UseAuthorization();
    app.Run();
    
  3. appsettings.json그래프 및 에이전트 ID 옵션을 구성합니다.

    경고

    클라이언트 비밀은 보안 위험으로 인해 에이전트 ID 청사진에 대한 프로덕션 환경에서 클라이언트 자격 증명으로 사용해서는 안 됩니다. 대신 관리 ID 또는 클라이언트 인증서와 함께 FIC(페더레이션 ID 자격 증명)와 같은 보다 안전한 인증 방법을 사용합니다. 이러한 메서드는 애플리케이션 구성 내에서 직접 중요한 비밀을 저장할 필요가 없도록 하여 향상된 보안을 제공합니다.

    {
      "AzureAd": {
        "Instance": "https://login.microsoftonline.com/",
        "TenantId": "<my-test-tenant>",
        "ClientId": "<agent-blueprint-client-id>",
        "ClientCredentials": [
          {
            "SourceType": "ClientSecret",
            "ClientSecret": "your-client-secret"
          }
        ]
      },
      "DownstreamApis": {
        "MicrosoftGraph": {
          "BaseUrl": "https://graph.microsoft.com/v1.0",
          "Scopes": ["User.Read", "User.ReadBasic.All"]
        }
      }
    }
    
  4. 이제 서비스를 통해 GraphServiceClient를 주입하여 Microsoft Graph를 호출할 수 있습니다. 서비스 공급자를 통해서도 가능합니다.

  • 에이전트 ID의 경우 이 메서드를 사용하여 WithAgentIdentity 앱 전용 토큰(자율 에이전트) 또는 사용자 토큰(대화형 에이전트)을 대신해서 획득할 수 있습니다. 앱 전용 토큰의 경우 속성을 RequestAppToken.로 설정합니다true. 사용자 토큰에 대해 대리로 위임된 경우, 속성을 RequestAppToken 또는 명시적으로 false로 설정하지 마세요.

    // Get the GraphServiceClient
    GraphServiceClient graphServiceClient = serviceProvider.GetRequiredService<GraphServiceClient>();
    
    string agentIdentity = "agent-identity-guid";
    
    // Call Microsoft Graph APIs with the agent identity for app only scenario
    var applications = await graphServiceClient.Applications
        .GetAsync(r => r.Options.WithAuthenticationOptions(options =>
        {
            options.WithAgentIdentity(agentIdentity);
            options.RequestAppToken = true; // Set to true for app only
        }));
    
    // Call Microsoft Graph APIs with the agent identity for on-behalf of user scenario
    var applications = await graphServiceClient.Applications
        .GetAsync(r => r.Options.WithAuthenticationOptions(options =>
        {
            options.WithAgentIdentity(agentIdentity);
            options.RequestAppToken = false; // False to show it's on-behalf of user
        }));
    
    • 에이전트의 사용자 계정 ID의 경우 UPN(사용자 계정 이름) 또는 OID(개체 ID)를 지정하여 메서드를 사용하여 WithAgentUserIdentity 에이전트의 사용자 계정을 식별할 수 있습니다.

      // Get the GraphServiceClient
      GraphServiceClient graphServiceClient = serviceProvider.GetRequiredService<GraphServiceClient>();
      
      string agentIdentity = "agent-identity-guid";
      
      // Call Microsoft Graph APIs with the agent's user account identity using UPN
      string userUpn = "user-upn";
      var me = await graphServiceClient.Me
          .GetAsync(r => r.Options.WithAuthenticationOptions(options =>
              options.WithAgentUserIdentity(agentIdentity, userUpn)));
      
      // Or using OID
      string userOid = "user-object-id";
      var me = await graphServiceClient.Me
          .GetAsync(r => r.Options.WithAuthenticationOptions(options =>
              options.WithAgentUserIdentity(agentIdentity, userOid)));