有多種方式可以從代理呼叫自訂 API。 根據你的情境,你可以使用 IDownstreamApi、 MicrosoftIdentityMessageHandler或 IAuthorizationHeaderProvider。 本指南說明了呼叫你自己受保護 API 的不同方法,涵蓋三種方式。
要從代理呼叫 API,你需要取得一個存取權杖,代理可以用來驗證自己對 API 的身份。 我們建議使用 Microsoft。Identity.Web SDK 用於.NET呼叫你的網頁 API。 此 SDK 簡化了取得與驗證憑證的流程。 其他語言則使用 Microsoft Entra ID Auth SDK(sidecar)。
先決條件
- 一個具有適當權限以呼叫目標 API 的代理身份。 你需要一個代表流程的使用者。
- 代理人的使用者帳號,並擁有適當權限來呼叫目標 API。
根據你的情況決定要採用哪種方法
以下表格將協助你決定採用哪種方法。 在大多數情況下,我們建議使用 IDownstreamApi。
| 方法 | 複雜性 | 靈活性 | 用例 |
|---|---|---|---|
IDownstreamApi |
低 | 中等 | 標準 REST API 與設定 |
MicrosoftIdentityMessageHandler |
中等 | 高 | 具備直接注入(DI)及可組合管線的 HttpClient |
IAuthorizationHeaderProvider |
高 | 非常高 | 對 HTTP 請求的完全控制 |
IDownstreamApi 是三種選項中呼叫受保護 API 的首選方式。 它高度可配置,且只需最小的程式碼修改。 它還提供自動代幣取得功能。
當你需要以下列出的物品時,請使用 IDownstreamApi :
- 你正在呼叫標準的 REST API
- 你需要以配置為導向的方法
- 你需要自動序列化/反序列化
- 你想寫最少的程式碼
調用您的 API
確定適合你的方法後,接著呼叫你自訂的網頁 API。
警告
由於安全風險,客戶端秘密不應在生產環境中作為代理身份藍圖的客戶端憑證使用。 相反地,應使用更安全的認證方法,例如 聯邦身份憑證(FIC)搭配管理身份 或用戶端憑證。 這些方法透過消除直接在應用程式配置中儲存敏感秘密的需求,提升安全性。
安裝所需的 NuGet 套件:
dotnet add package Microsoft.Identity.Web.DownstreamApi dotnet add package Microsoft.Identity.Web.AgentIdentitiesappsettings.json內的 Token 認證選項以及您的 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 } } }配置您的服務以增加下游 API 支援:
using Microsoft.AspNetCore.Authentication.OpenIdConnect; 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();使用
IDownstreamApi呼叫受保護的 API。 呼叫 API 時,你可以使用WithAgentIdentityorWithAgentUserIdentity方法指定代理身份或代理的使用者帳號身份。IDownstreamApi自動處理憑證取得並將存取憑證附加到請求中。對於
WithAgentIdentity,您可以使用僅應用程式代幣(自主代理人)或代表使用者(互動代理人)來呼叫 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)或物件識別碼(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's user account 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's user account 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); } }