语言

MicrosoftIdentityMessageHandler 类

定义

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

注解

此消息处理程序提供了一种灵活的、可组合的方式,用于向基于 HttpClient 的代码添加Microsoft标识身份验证。 它可用作IDownstreamApi开发人员希望保持对 HTTP 请求处理的直接控制,同时仍受益于Microsoft标识 Web 的身份验证功能的方案。

主要功能:

  • 所有传出请求的自动授权标头注入
  • 使用扩展方法的按请求身份验证选项
  • 使用令牌刷新自动 WWW-Authenticate 质询处理
  • 支持代理标识和托管标识方案
  • 全面的日志记录和错误处理
  • 多框架兼容性(.NET Framework 4.6.2+、.NET Standard 2.0+、.NET 5+)

WWW-Authenticate 质询处理:

当下游 API 返回一个 401 未经授权的响应,其中包含具有其他声明的持有者质询的 WWW-Authenticate 标头时,此处理程序将自动尝试使用请求的声明获取新令牌并重试请求。 这对于需要其他声明的条件访问方案特别有用。

适用于

另请参阅