從代理程式使用 .NET 呼叫 Microsoft 圖形 API

本文說明如何利用代理身份或代理的使用者帳號,從代理呼叫 Microsoft 圖形 API。

要從代理呼叫 API,你需要取得一個存取權杖,代理可以用來驗證自己對 API 的身份。 我們建議使用 Microsoft。Identity.Web SDK 用於.NET呼叫你的網頁 API。 此 SDK 簡化了取得與驗證憑證的流程。 對於其他語言,請使用 Microsoft Entra ID Auth SDK (sidecar)

先決條件

  • 一個具有適當權限以呼叫目標 API 的代理身份。 你需要一個代表流程的使用者。
  • 代理人的使用者帳號,並擁有適當權限來呼叫目標 API。

呼叫 Microsoft 圖形 API

  1. 安裝 Microsoft.Identity.Web.GraphServiceClient 以負責 Graph SDK 的認證,以及 Microsoft.Identity.Web.AgentIdentities 套件,以新增對代理身份的支援。

    dotnet add package Microsoft.Identity.Web.GraphServiceClient
    dotnet add package Microsoft.Identity.Web.AgentIdentities
    
  2. 在您的服務集合中加入對 Microsoft Graph 與代理身份的支援。

    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中設定 Graph 與代理身份選項。

    警告

    由於安全風險,客戶端秘密不應在生產環境中作為代理身份藍圖的客戶端憑證使用。 相反地,應使用更安全的認證方法,例如 聯邦身份憑證(FIC)搭配管理身份 或用戶端憑證。 這些方法透過消除直接在應用程式配置中儲存敏感秘密的需求,提升安全性。

    {
      "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。

  • 對於代理身份,你可以使用 WithAgentIdentity 方法取得應用程式專用代幣(自主代理)或代表使用者的代幣(互動代理)。 對於僅 app 的標記,將屬性設 RequestAppTokentrue。 針對代表使用者的委派代幣,請不要設定 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
        }));
    
    • 對於代理的使用者帳號身份,您可以使用此 WithAgentUserIdentity 方法指定使用者主體名稱(UPN)或物件身份碼(OID)來識別代理的使用者帳號。

      // 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)));