MicrosoftIdentityMessageHandler 클래스
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
DelegatingHandler 사용 및 MicrosoftIdentityMessageHandlerOptions.를 사용하여 IAuthorizationHeaderProvider 나가는 HTTP 요청에 권한 부여 헤더를 자동으로 추가하는 구현입니다.
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 인증을 추가하는 유연하고 구성 가능한 방법을 제공합니다. 개발자가 ID 웹의 인증 기능을 Microsoft 이점을 유지하면서 HTTP 요청 처리를 직접 제어하려는 시나리오의 대안 IDownstreamApi 으로 사용됩니다.
주요 기능:
- 나가는 모든 요청에 대한 자동 권한 부여 헤더 삽입
- 확장 메서드를 사용하는 요청별 인증 옵션
- 토큰 새로 고침을 사용한 자동 WWW-Authenticate 챌린지 처리
- 에이전트 ID 및 관리 ID 시나리오 지원
- 포괄적인 로깅 및 오류 처리
- 다중 프레임워크 호환성(.NET Framework 4.6.2 이상, .NET Standard 2.0 이상, .NET 5 이상)
WWW-Authenticate 챌린지 처리:
다운스트림 API가 추가 클레임이 있는 전달자 챌린지가 포함된 WWW-Authenticate 헤더로 401 권한 없는 응답을 반환하면 이 처리기는 요청된 클레임으로 새 토큰을 획득하고 요청을 다시 시도합니다. 이는 추가 클레임이 필요한 조건부 액세스 시나리오에 특히 유용합니다.
생성자
메서드
| Name | Description |
|---|---|
| SendAsync(HttpRequestMessage, CancellationToken) |
자동 인증 헤더 삽입을 사용하여 HTTP 요청을 보냅니다. 필요한 경우 추가 클레임을 사용하여 토큰 새로 고침을 시도하여 WWW-Authenticate 문제를 처리합니다. |