語言

MicrosoftIdentityMessageHandler 類別

定義

一種 DelegatingHandler 實作,能自動為外發出的 HTTP 請求加上授權標頭,使用 IAuthorizationHeaderProvider 和 MicrosoftIdentityMessageHandlerOptions。

public class MicrosoftIdentityMessageHandler : System.Net.Http.DelegatingHandler
type MicrosoftIdentityMessageHandler = class
    inherit DelegatingHandler
Public Class MicrosoftIdentityMessageHandler
Inherits DelegatingHandler
繼承
MicrosoftIdentityMessageHandler

範例

依賴注入的基本設定:

// In Program.cs or Startup.cs
services.AddHttpClient("MyApiClient", client =>
{
    client.BaseAddress = new Uri("https://api.example.com");
})
.AddHttpMessageHandler(serviceProvider => new MicrosoftIdentityMessageHandler(
    serviceProvider.GetRequiredService<IAuthorizationHeaderProvider>(),
    new MicrosoftIdentityMessageHandlerOptions
    {
        Scopes = { "https://api.example.com/.default" }
    }));

// In a controller or service
public class ApiService
{
    private readonly HttpClient _httpClient;

    public ApiService(IHttpClientFactory httpClientFactory)
    {
        _httpClient = httpClientFactory.CreateClient("MyApiClient");
    }

    public async Task<string> GetDataAsync()
    {
        var response = await _httpClient.GetAsync("/api/data");
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }
}

按請求進行的認證選項:

// Override scopes for a specific request
var request = new HttpRequestMessage(HttpMethod.Get, "/api/sensitive-data")
    .WithAuthenticationOptions(options =>
    {
        options.Scopes.Add("https://api.example.com/sensitive.read");
        options.RequestAppToken = true;
    });

var response = await _httpClient.SendAsync(request);

代理身份的使用:

var request = new HttpRequestMessage(HttpMethod.Get, "/api/agent-data")
    .WithAuthenticationOptions(options =>
    {
        options.Scopes.Add("https://graph.microsoft.com/.default");
        options.WithAgentIdentity("agent-application-id");
        options.RequestAppToken = true;
    });

var response = await _httpClient.SendAsync(request);

手動實例化:

var headerProvider = serviceProvider.GetRequiredService<IAuthorizationHeaderProvider>();
var logger = serviceProvider.GetService<ILogger<MicrosoftIdentityMessageHandler>>();

var handler = new MicrosoftIdentityMessageHandler(
    headerProvider,
    new MicrosoftIdentityMessageHandlerOptions
    {
        Scopes = { "https://graph.microsoft.com/.default" }
    },
    logger);

using var httpClient = new HttpClient(handler);
var response = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me");

錯誤處理:

try
{
    var response = await _httpClient.SendAsync(request, cancellationToken);
    response.EnsureSuccessStatusCode();
    return await response.Content.ReadAsStringAsync();
}
catch (MicrosoftIdentityAuthenticationException authEx)
{
    // Handle authentication-specific failures
    _logger.LogError(authEx, "Authentication failed: {Message}", authEx.Message);
    throw;
}
catch (HttpRequestException httpEx)
{
    // Handle other HTTP failures
    _logger.LogError(httpEx, "HTTP request failed: {Message}", httpEx.Message);
    throw;
}

備註

此訊息處理器提供一種靈活且可組合的方式,將 Microsoft 身份驗證加入基於 HttpClient 的程式碼。 它作為開發者希望在同時享受 Microsoft Identity Web 認證功能的情況下,維持對 HTTP 請求處理的直接控制的替代方案IDownstreamApi。

主要功能:

  • 所有外發出請求自動授權標頭注入
  • 使用擴充方法的逐請求認證選項
  • 自動 WWW-Authenticate 挑戰處理並有代幣更新
  • 支援代理身份與管理身份情境
  • 全面的日誌記錄與錯誤處理
  • 多框架相容性(.NET Framework 4.6.2+、.NET Standard 2.0+、.NET 5+)

WWW-Authenticate 挑戰處理:

當下游 API 回傳帶有 WWW-Authenticate 標頭且包含承載挑戰及額外權利要求的 401 未授權回應時,該處理器會自動嘗試取得包含該請求的新憑證並重新嘗試該請求。 這對於需要額外理賠的條件存取情境特別有用。

建構函式

名稱 Description
MicrosoftIdentityMessageHandler(IAuthorizationHeaderProvider, MicrosoftIdentityMessageHandlerOptions, ILogger<MicrosoftIdentityMessageHandler>)

初始化 MicrosoftIdentityMessageHandler 類別的新執行個體。

MicrosoftIdentityMessageHandler(IAuthorizationHeaderProvider, MicrosoftIdentityMessageHandlerOptions, IMsalMtlsHttpClientFactory, ILogger<MicrosoftIdentityMessageHandler>)

初始化一個支援 mTLS PoP 令牌綁定的新類別實例 MicrosoftIdentityMessageHandler 。

方法

名稱 Description
SendAsync(HttpRequestMessage, CancellationToken)

發送帶有自動認證標頭注入的 HTTP 請求。 如有需要,會嘗試代幣更新並提出額外申請,來處理 WWW-Authenticate 挑戰。

適用於

另請參閱