MicrosoftIdentityMessageHandler クラス

定義

IAuthorizationHeaderProviderMicrosoftIdentityMessageHandlerOptionsを使用して送信 HTTP 要求に承認ヘッダーを自動的に追加するDelegatingHandler実装。

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

エージェント ID の使用方法:

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;
}

注釈

このメッセージ ハンドラーは、httpClient ベースのコードにMicrosoft ID 認証を追加するための柔軟で構成可能な方法を提供します。 これは、開発者が MICROSOFT Identity Web の認証機能の恩恵を受けながら、HTTP 要求処理を直接制御する必要があるシナリオのIDownstreamApiの代替手段として機能します。

主な特徴:

  • すべての送信要求の自動承認ヘッダー挿入
  • 拡張メソッドを使用した要求ごとの認証オプション
  • トークン更新による自動 WWW-Authenticate チャレンジ処理
  • エージェント ID とマネージド ID のシナリオのサポート
  • 包括的なログ記録とエラー処理
  • マルチフレームワークの互換性 (.NET Framework 4.6.2 以降、.NET Standard 2.0 以降、.NET 5 以降)

WWW-Authenticate チャレンジ処理:

ダウンストリーム API が、追加の要求を含む Bearer チャレンジを含む WWW-Authenticate ヘッダーを含む 401 Unauthorized 応答を返すと、このハンドラーは自動的に要求された要求を含む新しいトークンの取得を試み、要求を再試行します。 これは、追加の要求が必要な条件付きアクセス シナリオで特に便利です。

コンストラクター

名前 説明
MicrosoftIdentityMessageHandler(IAuthorizationHeaderProvider, MicrosoftIdentityMessageHandlerOptions, ILogger<MicrosoftIdentityMessageHandler>)

MicrosoftIdentityMessageHandler クラスの新しいインスタンスを初期化します。

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

mTLS PoP トークン バインドのサポートを使用して、 MicrosoftIdentityMessageHandler クラスの新しいインスタンスを初期化します。

メソッド

名前 説明
SendAsync(HttpRequestMessage, CancellationToken)

認証ヘッダーの自動挿入を使用して HTTP 要求を送信します。 必要に応じて、追加の要求を使用してトークンの更新を試みることで、WWW-Authenticate チャレンジを処理します。

適用対象

こちらもご覧ください