Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Sep 26, 2025

Implementation Complete: MicrosoftIdentityMessageHandler

Fixes #3502

FULLY IMPLEMENTED - The MicrosoftIdentityMessageHandler has been successfully implemented according to the GitHub issue specification.

🎯 Core Implementation

  • MicrosoftIdentityMessageHandler: Main delegating handler class with async-first API
  • MicrosoftIdentityMessageHandlerOptions: Configuration class for scopes and options
  • HttpRequestMessage Extensions: Per-request authentication configuration
  • MicrosoftIdentityAuthenticationException: Specific exception for authentication failures
  • Multi-Framework Support: net462, net472, netstandard2.0, net8.0, net9.0
  • PublicAPI Compliance: All APIs properly declared in PublicAPI files

🚀 Key Features Delivered

Flexible Authentication: Uses IAuthorizationHeaderProvider and AuthorizationHeaderProviderOptions
Per-Client Configuration: Default options can be set at handler creation
Per-Request Override: Options can be configured per HTTP request
Modern .NET APIs: Uses HttpRequestMessage.Options (with fallback for older frameworks)
Challenge Handling: Robust WWW-Authenticate challenge detection using MSAL's WwwAuthenticateParameters
Error Handling: Actionable exceptions with clear error messages
Logging Integration: Optional ILogger<MicrosoftIdentityMessageHandler> support with enhanced logging
Performance Optimized: Efficient challenge handling with proper resource management

📖 Usage Examples (All Working)

1. DI Setup:

services.AddHttpClient("ContosoApi", c => { /* base address */ })
    .AddHttpMessageHandler(sp => new MicrosoftIdentityMessageHandler(
        sp.GetRequiredService<IAuthorizationHeaderProvider>(),
        new MicrosoftIdentityMessageHandlerOptions { Scopes = { "api://contoso-api/.default" } }
    ));

2. Per-Request Override:

var req = new HttpRequestMessage(HttpMethod.Get, "/todos")
    .WithAuthenticationOptions(o => o.Scopes.Add("custom.scope"));
await _client.SendAsync(req);

3. Manual Instantiation:

var client = new HttpClient(new MicrosoftIdentityMessageHandler(provider));
var req = new HttpRequestMessage(HttpMethod.Get, "/users")
    .WithAuthenticationOptions(o => o.Scopes.Add("https://graph.microsoft.com/.default"));

4. Error Handling:

try {
    var response = await _client.SendAsync(request);
    response.EnsureSuccessStatusCode();
} catch (MicrosoftIdentityAuthenticationException ex) {
    // Handle token acquisition/challenge failures
}

🧪 Testing & Quality

  • Build Success: All target frameworks compile without errors
  • Unit Tests: 8 tests created, all passing (net8.0 and net9.0)
  • API Validation: Constructor validation, option setting/getting, exception handling
  • Cross-Platform: Compatible with .NET Framework, .NET Standard, and modern .NET

🔧 Technical Highlights

  • Async-First: All token acquisition operations are async
  • Type-Safe: Strong typing for all configuration options
  • Composable: Works with existing HttpClient infrastructure
  • Lightweight: Minimal dependencies, reuses existing Microsoft Identity Web abstractions
  • Factorized: Shares authentication logic patterns with existing handlers using MSAL's WWW-Authenticate parser
  • Enhanced Logging: Comprehensive logging for challenge detection, retry status, and failures

📋 Recent Enhancement (Latest Commit)

Code Review Improvements: Based on comprehensive code review feedback

  • MSAL WWW-Authenticate Parser: Replaced custom regex with WwwAuthenticateParameters.GetClaimChallengeFromResponseHeaders() for robust, well-tested challenge parsing
  • Simplified Error Handling: Removed try/catch that was suppressing errors in challenge retry - errors now propagate naturally
  • Enhanced Logging: Added detailed logging for retry response status, including detection of subsequent 401s and WWW-Authenticate headers
  • Improved Documentation: Enhanced exception documentation with clear explanation of WWW-Authenticate challenge handling behavior
  • Log Level Adjustments: Changed no-claims-found message from Debug to Warning for better visibility
  • Code Quality: Fixed string comparison to use ordinal comparison for better performance and correctness

📋 Files Added/Modified

  • src/Microsoft.Identity.Web.TokenAcquisition/MicrosoftIdentityMessageHandler.cs
  • src/Microsoft.Identity.Web.TokenAcquisition/MicrosoftIdentityMessageHandlerOptions.cs
  • src/Microsoft.Identity.Web.TokenAcquisition/HttpRequestMessageAuthenticationExtensions.cs
  • src/Microsoft.Identity.Web.TokenAcquisition/MicrosoftIdentityAuthenticationException.cs
  • src/Microsoft.Identity.Web.TokenAcquisition/GlobalSuppressions.cs
  • tests/Microsoft.Identity.Web.Test/MicrosoftIdentityMessageHandlerNewTests.cs
  • PublicAPI files for all target frameworks (10 files updated)
  • AgentIdentities README documentation (section 7 added)

This implementation provides developers with a flexible, composable alternative to DownstreamApi that integrates seamlessly with existing HttpClient-based codebases while leveraging Microsoft Identity Web's complete authentication infrastructure, now enhanced with MSAL's proven WWW-Authenticate parsing and comprehensive logging.


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot AI changed the title [WIP] Spec: Add MicrosoftIdentityMessageHandler using IAuthorizationHeaderProvider for flexible authentication in HttpClient Add MicrosoftIdentityMessageHandler for flexible HttpClient authentication Sep 26, 2025
Copilot AI requested a review from jmprieur September 26, 2025 22:10
Copilot finished work on behalf of jmprieur September 26, 2025 22:10
Copilot AI requested a review from jmprieur September 26, 2025 23:33
Copilot finished work on behalf of jmprieur September 26, 2025 23:33
Copilot finished work on behalf of jmprieur September 26, 2025 23:42
Copilot AI requested a review from jmprieur September 26, 2025 23:42
Copilot finished work on behalf of jmprieur September 27, 2025 00:01
@jmprieur jmprieur marked this pull request as ready for review September 27, 2025 00:06
@jmprieur jmprieur requested a review from a team as a code owner September 27, 2025 00:06
Copilot AI requested a review from jmprieur September 27, 2025 00:24
Copilot finished work on behalf of jmprieur September 27, 2025 00:24
This was referenced Oct 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Spec: Add MicrosoftIdentityMessageHandler using IAuthorizationHeaderProvider for flexible authentication in HttpClient

5 participants