diff --git a/docs/calling-downstream-apis/custom-apis.md b/docs/calling-downstream-apis/custom-apis.md
index 7d8129e8f..0482e4113 100644
--- a/docs/calling-downstream-apis/custom-apis.md
+++ b/docs/calling-downstream-apis/custom-apis.md
@@ -367,16 +367,14 @@ services.AddHttpClient("DownstreamApiClient", client =>
client.BaseAddress = new Uri("https://api.example.com");
})
.AddMicrosoftIdentityMessageHandler(
- configuration.GetSection("DownstreamApi"),
- "DownstreamApi");
+ configuration.GetSection("DownstreamApi"));
services.AddHttpClient("GraphClient", client =>
{
client.BaseAddress = new Uri("https://graph.microsoft.com");
})
.AddMicrosoftIdentityMessageHandler(
- configuration.GetSection("GraphApi"),
- "GraphApi");
+ configuration.GetSection("GraphApi"));
```
### Configuration Examples
@@ -479,24 +477,21 @@ services.AddHttpClient("CustomerApiClient", client =>
client.BaseAddress = new Uri("https://customer-api.example.com");
})
.AddMicrosoftIdentityMessageHandler(
- downstreamApis.GetSection("CustomerApi"),
- "CustomerApi");
+ downstreamApis.GetSection("CustomerApi"));
services.AddHttpClient("OrderApiClient", client =>
{
client.BaseAddress = new Uri("https://order-api.example.com");
})
.AddMicrosoftIdentityMessageHandler(
- downstreamApis.GetSection("OrderApi"),
- "OrderApi");
+ downstreamApis.GetSection("OrderApi"));
services.AddHttpClient("InventoryApiClient", client =>
{
client.BaseAddress = new Uri("https://inventory-api.example.com");
})
.AddMicrosoftIdentityMessageHandler(
- downstreamApis.GetSection("InventoryApi"),
- "InventoryApi");
+ downstreamApis.GetSection("InventoryApi"));
```
### Per-Request Options
@@ -614,8 +609,7 @@ services.AddHttpClient("SecureApiClient", client =>
client.BaseAddress = new Uri("https://secure-api.example.com");
})
.AddMicrosoftIdentityMessageHandler(
- configuration.GetSection("DownstreamApis:SecureApi"),
- "SecureApi");
+ configuration.GetSection("DownstreamApis:SecureApi"));
```
##### Inline Configuration
diff --git a/docs/calling-downstream-apis/token-binding.md b/docs/calling-downstream-apis/token-binding.md
index 8eecaf41d..4e74c98f3 100644
--- a/docs/calling-downstream-apis/token-binding.md
+++ b/docs/calling-downstream-apis/token-binding.md
@@ -409,8 +409,7 @@ services.AddHttpClient("SecureApiClient", client =>
client.BaseAddress = new Uri("https://secure-api.example.com");
})
.AddMicrosoftIdentityMessageHandler(
- configuration.GetSection("DownstreamApis:SecureApi"),
- "SecureApi");
+ configuration.GetSection("DownstreamApis:SecureApi"));
```
#### Per-Request Token Binding
diff --git a/src/Microsoft.Identity.Web.TokenAcquisition/MicrosoftIdentityHttpClientBuilderExtensions.cs b/src/Microsoft.Identity.Web.TokenAcquisition/MicrosoftIdentityHttpClientBuilderExtensions.cs
index dbfe3741e..3d10b5179 100644
--- a/src/Microsoft.Identity.Web.TokenAcquisition/MicrosoftIdentityHttpClientBuilderExtensions.cs
+++ b/src/Microsoft.Identity.Web.TokenAcquisition/MicrosoftIdentityHttpClientBuilderExtensions.cs
@@ -25,7 +25,7 @@ namespace Microsoft.Identity.Web
/// will automatically add authorization headers to outgoing HTTP requests based on the configured options.
///
///
- /// Four overloads are provided to support different configuration scenarios:
+ /// The overloads support different configuration scenarios:
///
///
/// - Parameterless: For scenarios where options are set per-request
@@ -58,8 +58,7 @@ namespace Microsoft.Identity.Web
///
/// services.AddHttpClient("GraphClient")
/// .AddMicrosoftIdentityMessageHandler(
- /// configuration.GetSection("DownstreamApi"),
- /// "DownstreamApi");
+ /// configuration.GetSection("DownstreamApi"));
///
///
/// Parameterless for per-request configuration:
@@ -325,10 +324,9 @@ public static IHttpClientBuilder AddMicrosoftIdentityMessageHandler(
///
/// The to configure.
/// The configuration section containing the authentication options.
- /// The name of the configuration section (used for diagnostics).
/// The for method chaining.
///
- /// Thrown when , , or is .
+ /// Thrown when or is .
///
///
///
@@ -363,16 +361,14 @@ public static IHttpClientBuilder AddMicrosoftIdentityMessageHandler(
/// client.BaseAddress = new Uri("https://api.example.com");
/// })
/// .AddMicrosoftIdentityMessageHandler(
- /// configuration.GetSection("DownstreamApi"),
- /// "DownstreamApi");
+ /// configuration.GetSection("DownstreamApi"));
///
/// services.AddHttpClient("GraphClient", client =>
/// {
/// client.BaseAddress = new Uri("https://graph.microsoft.com");
/// })
/// .AddMicrosoftIdentityMessageHandler(
- /// configuration.GetSection("GraphApi"),
- /// "GraphApi");
+ /// configuration.GetSection("GraphApi"));
///
///
/// Use the clients:
@@ -406,6 +402,39 @@ public static IHttpClientBuilder AddMicrosoftIdentityMessageHandler(
///
[RequiresUnreferencedCode("Calls Microsoft.Extensions.Configuration.ConfigurationBinder.Bind(IConfiguration, Object).")]
[RequiresDynamicCode("Calls Microsoft.Extensions.Configuration.ConfigurationBinder.Bind(IConfiguration, Object).")]
+ public static IHttpClientBuilder AddMicrosoftIdentityMessageHandler(
+ this IHttpClientBuilder builder,
+ IConfiguration configuration)
+ {
+ if (builder is null)
+ {
+ throw new ArgumentNullException(nameof(builder));
+ }
+
+ if (configuration is null)
+ {
+ throw new ArgumentNullException(nameof(configuration));
+ }
+
+ return builder.AddMicrosoftIdentityMessageHandler(options => configuration.Bind(options));
+ }
+
+ ///
+ /// Adds a to the HTTP client pipeline with options bound from IConfiguration.
+ ///
+ /// The to configure.
+ /// The configuration section containing the authentication options.
+ /// Retained for compatibility. This value is checked for null but is otherwise unused.
+ /// The for method chaining.
+ ///
+ /// Thrown when , , or is .
+ ///
+ ///
+ /// The supplied is bound directly; does not select a section or name options.
+ /// Prefer for new code.
+ ///
+ [RequiresUnreferencedCode("Calls Microsoft.Extensions.Configuration.ConfigurationBinder.Bind(IConfiguration, Object).")]
+ [RequiresDynamicCode("Calls Microsoft.Extensions.Configuration.ConfigurationBinder.Bind(IConfiguration, Object).")]
public static IHttpClientBuilder AddMicrosoftIdentityMessageHandler(
this IHttpClientBuilder builder,
IConfiguration configuration,
@@ -426,18 +455,7 @@ public static IHttpClientBuilder AddMicrosoftIdentityMessageHandler(
throw new ArgumentNullException(nameof(sectionName));
}
- return builder.AddHttpMessageHandler(sp =>
- {
- var options = new MicrosoftIdentityMessageHandlerOptions();
- configuration.Bind(options);
-
- return new MicrosoftIdentityMessageHandler(
- sp.GetRequiredService(),
- options,
- GetMsalMtlsHttpClientFactory(sp),
- GetCredentialsProvider(sp),
- GetLogger(sp));
- });
+ return builder.AddMicrosoftIdentityMessageHandler(configuration);
}
private static IMsalMtlsHttpClientFactory? GetMsalMtlsHttpClientFactory(IServiceProvider services)
diff --git a/src/Microsoft.Identity.Web.TokenAcquisition/PublicAPI/NetCore/PublicAPI.Unshipped.txt b/src/Microsoft.Identity.Web.TokenAcquisition/PublicAPI/NetCore/PublicAPI.Unshipped.txt
index 7dc5c5811..f7d63afda 100644
--- a/src/Microsoft.Identity.Web.TokenAcquisition/PublicAPI/NetCore/PublicAPI.Unshipped.txt
+++ b/src/Microsoft.Identity.Web.TokenAcquisition/PublicAPI/NetCore/PublicAPI.Unshipped.txt
@@ -1 +1,2 @@
#nullable enable
+static Microsoft.Identity.Web.MicrosoftIdentityHttpClientBuilderExtensions.AddMicrosoftIdentityMessageHandler(this Microsoft.Extensions.DependencyInjection.IHttpClientBuilder! builder, Microsoft.Extensions.Configuration.IConfiguration! configuration) -> Microsoft.Extensions.DependencyInjection.IHttpClientBuilder!
diff --git a/src/Microsoft.Identity.Web.TokenAcquisition/PublicAPI/NetFramework/PublicAPI.Unshipped.txt b/src/Microsoft.Identity.Web.TokenAcquisition/PublicAPI/NetFramework/PublicAPI.Unshipped.txt
index 7dc5c5811..f7d63afda 100644
--- a/src/Microsoft.Identity.Web.TokenAcquisition/PublicAPI/NetFramework/PublicAPI.Unshipped.txt
+++ b/src/Microsoft.Identity.Web.TokenAcquisition/PublicAPI/NetFramework/PublicAPI.Unshipped.txt
@@ -1 +1,2 @@
#nullable enable
+static Microsoft.Identity.Web.MicrosoftIdentityHttpClientBuilderExtensions.AddMicrosoftIdentityMessageHandler(this Microsoft.Extensions.DependencyInjection.IHttpClientBuilder! builder, Microsoft.Extensions.Configuration.IConfiguration! configuration) -> Microsoft.Extensions.DependencyInjection.IHttpClientBuilder!
diff --git a/tests/DevApps/MtlsPop/MtlsPopClient/Program.cs b/tests/DevApps/MtlsPop/MtlsPopClient/Program.cs
index 8b8d31bc3..7ebcbefa4 100644
--- a/tests/DevApps/MtlsPop/MtlsPopClient/Program.cs
+++ b/tests/DevApps/MtlsPop/MtlsPopClient/Program.cs
@@ -28,8 +28,7 @@ public static async Task Main(string[] args)
tokenAcquirerFactory.Configuration.GetSection("WebApi")["BaseUrl"]!);
})
.AddMicrosoftIdentityMessageHandler(
- tokenAcquirerFactory.Configuration.GetSection("WebApi"),
- "WebApi");
+ tokenAcquirerFactory.Configuration.GetSection("WebApi"));
tokenAcquirerFactory.Services.AddMicrosoftGraph();
diff --git a/tests/Microsoft.Identity.Web.Test/MicrosoftIdentityHttpClientBuilderExtensionsTests.cs b/tests/Microsoft.Identity.Web.Test/MicrosoftIdentityHttpClientBuilderExtensionsTests.cs
index 2dcf15b5f..7caa41451 100644
--- a/tests/Microsoft.Identity.Web.Test/MicrosoftIdentityHttpClientBuilderExtensionsTests.cs
+++ b/tests/Microsoft.Identity.Web.Test/MicrosoftIdentityHttpClientBuilderExtensionsTests.cs
@@ -4,10 +4,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using System.Net;
using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Identity.Abstractions;
+using Microsoft.Identity.Web.Test.Common.Mocks;
using NSubstitute;
using Xunit;
@@ -151,20 +155,27 @@ public void AddMicrosoftIdentityMessageHandler_WithDelegate_RegistersHandlerWith
Assert.NotNull(client);
}
- [Fact]
- public void AddMicrosoftIdentityMessageHandler_WithConfiguration_WithNullBuilder_ThrowsArgumentNullException()
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public void AddMicrosoftIdentityMessageHandler_WithConfiguration_WithNullBuilder_ThrowsArgumentNullException(bool useLegacyOverload)
{
// Arrange
IHttpClientBuilder? builder = null;
var configuration = new ConfigurationBuilder().Build();
// Act & Assert
- Assert.Throws(() =>
- builder!.AddMicrosoftIdentityMessageHandler(configuration, "TestSection"));
+ var exception = Assert.Throws(() =>
+ useLegacyOverload
+ ? builder!.AddMicrosoftIdentityMessageHandler(configuration, "TestSection")
+ : builder!.AddMicrosoftIdentityMessageHandler(configuration));
+ Assert.Equal("builder", exception.ParamName);
}
- [Fact]
- public void AddMicrosoftIdentityMessageHandler_WithConfiguration_WithNullConfiguration_ThrowsArgumentNullException()
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public void AddMicrosoftIdentityMessageHandler_WithConfiguration_WithNullConfiguration_ThrowsArgumentNullException(bool useLegacyOverload)
{
// Arrange
var services = new ServiceCollection();
@@ -173,8 +184,11 @@ public void AddMicrosoftIdentityMessageHandler_WithConfiguration_WithNullConfigu
IConfiguration? configuration = null;
// Act & Assert
- Assert.Throws(() =>
- builder.AddMicrosoftIdentityMessageHandler(configuration!, "TestSection"));
+ var exception = Assert.Throws(() =>
+ useLegacyOverload
+ ? builder.AddMicrosoftIdentityMessageHandler(configuration!, "TestSection")
+ : builder.AddMicrosoftIdentityMessageHandler(configuration!));
+ Assert.Equal("configuration", exception.ParamName);
}
[Fact]
@@ -188,18 +202,24 @@ public void AddMicrosoftIdentityMessageHandler_WithConfiguration_WithNullSection
string? sectionName = null;
// Act & Assert
- Assert.Throws(() =>
+ var exception = Assert.Throws(() =>
builder.AddMicrosoftIdentityMessageHandler(configuration, sectionName!));
+ Assert.Equal("sectionName", exception.ParamName);
}
- [Fact]
- public void AddMicrosoftIdentityMessageHandler_WithConfiguration_RegistersHandlerWithBoundOptions()
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public async Task AddMicrosoftIdentityMessageHandler_WithConfiguration_RegistersHandlerWithBoundOptions(bool useLegacyOverload)
{
// Arrange
var configurationData = new Dictionary
{
- { "DownstreamApi:Scopes:0", "https://graph.microsoft.com/.default" },
- { "DownstreamApi:Scopes:1", "User.Read" }
+ { "DownstreamApis:Graph:Scopes:0", "https://graph.microsoft.com/.default" },
+ { "DownstreamApis:Graph:Scopes:1", "User.Read" },
+ { "DownstreamApis:Graph:RequestAppToken", "false" },
+ { "DownstreamApis:Other:Scopes:0", "https://api.example.com/.default" },
+ { "DownstreamApis:Other:RequestAppToken", "true" }
};
var configuration = new ConfigurationBuilder()
@@ -208,19 +228,95 @@ public void AddMicrosoftIdentityMessageHandler_WithConfiguration_RegistersHandle
var services = new ServiceCollection();
services.AddSingleton(_mockHeaderProvider);
- var builder = services.AddHttpClient("TestClient");
+ _mockHeaderProvider.CreateAuthorizationHeaderAsync(Enumerable.Empty())
+ .ReturnsForAnyArgs("Bearer test-token");
// Act
- builder.AddMicrosoftIdentityMessageHandler(
- configuration.GetSection("DownstreamApi"),
- "DownstreamApi");
+ foreach (var name in new[] { "Graph", "Other" })
+ {
+ var builder = services.AddHttpClient(name)
+ .ConfigurePrimaryHttpMessageHandler(() => new MockHttpMessageHandler
+ {
+ ExpectedMethod = HttpMethod.Get,
+ ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
+ {
+ Content = new StringContent(string.Empty)
+ }
+ });
+ var section = configuration.GetSection($"DownstreamApis:{name}");
+ var result = useLegacyOverload
+ ? builder.AddMicrosoftIdentityMessageHandler(section, "UnusedSectionName")
+ : builder.AddMicrosoftIdentityMessageHandler(section);
+ Assert.Same(builder, result);
+ }
+
+ using var serviceProvider = services.BuildServiceProvider();
+ var httpClientFactory = serviceProvider.GetRequiredService();
+ foreach (var name in new[] { "Graph", "Other" })
+ {
+ using var client = httpClientFactory.CreateClient(name);
+ using var response = await client.GetAsync("https://example.com");
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ }
// Assert
- var serviceProvider = services.BuildServiceProvider();
- var httpClientFactory = serviceProvider.GetRequiredService();
- var client = httpClientFactory.CreateClient("TestClient");
-
- Assert.NotNull(client);
+ await _mockHeaderProvider.Received(1).CreateAuthorizationHeaderAsync(
+ Arg.Is>(scopes => scopes.SequenceEqual(new[] { "https://graph.microsoft.com/.default", "User.Read" })),
+ Arg.Is(options => !options.RequestAppToken),
+ cancellationToken: Arg.Any());
+ await _mockHeaderProvider.Received(1).CreateAuthorizationHeaderAsync(
+ Arg.Is>(scopes => scopes.SequenceEqual(new[] { "https://api.example.com/.default" })),
+ Arg.Is(options => options.RequestAppToken),
+ cancellationToken: Arg.Any());
+ }
+
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public async Task AddMicrosoftIdentityMessageHandler_WithConfiguration_BindsOptionsWhenHandlerIsCreated(bool useLegacyOverload)
+ {
+ // Arrange
+ var configuration = new ConfigurationBuilder().AddInMemoryCollection().Build();
+ var services = new ServiceCollection();
+ services.AddSingleton(_mockHeaderProvider);
+ _mockHeaderProvider.CreateAuthorizationHeaderAsync(Enumerable.Empty())
+ .ReturnsForAnyArgs("******");
+
+ var builder = services.AddHttpClient("TestClient")
+ .ConfigurePrimaryHttpMessageHandler(() => new MockHttpMessageHandler
+ {
+ ExpectedMethod = HttpMethod.Get,
+ ResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
+ {
+ Content = new StringContent(string.Empty)
+ }
+ });
+ var section = configuration.GetSection("MutableApi");
+
+ // Act
+ if (useLegacyOverload)
+ {
+ builder.AddMicrosoftIdentityMessageHandler(section, "UnusedSectionName");
+ }
+ else
+ {
+ builder.AddMicrosoftIdentityMessageHandler(section);
+ }
+
+ configuration["MutableApi:Scopes:0"] = "updated-scope";
+ configuration["MutableApi:RequestAppToken"] = "true";
+
+ using var serviceProvider = services.BuildServiceProvider();
+ using var client = serviceProvider.GetRequiredService()
+ .CreateClient("TestClient");
+ using var response = await client.GetAsync("https://example.com");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ await _mockHeaderProvider.Received(1).CreateAuthorizationHeaderAsync(
+ Arg.Is>(scopes => scopes.SequenceEqual(new[] { "updated-scope" })),
+ Arg.Is(options => options.RequestAppToken),
+ cancellationToken: Arg.Any());
}
[Fact]
@@ -286,8 +382,10 @@ public void AddMicrosoftIdentityMessageHandler_ReturnsBuilder_AllowsChaining()
Assert.Same(builder, result);
}
- [Fact]
- public void AddMicrosoftIdentityMessageHandler_WithConfiguration_EmptyConfiguration_RegistersHandlerWithEmptyOptions()
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public void AddMicrosoftIdentityMessageHandler_WithConfiguration_EmptyConfiguration_RegistersHandlerWithEmptyOptions(bool useLegacyOverload)
{
// Arrange
var configuration = new ConfigurationBuilder().Build();
@@ -296,9 +394,10 @@ public void AddMicrosoftIdentityMessageHandler_WithConfiguration_EmptyConfigurat
var builder = services.AddHttpClient("TestClient");
// Act
- builder.AddMicrosoftIdentityMessageHandler(
- configuration.GetSection("NonExistent"),
- "NonExistent");
+ var section = configuration.GetSection("NonExistent");
+ var result = useLegacyOverload
+ ? builder.AddMicrosoftIdentityMessageHandler(section, "NonExistent")
+ : builder.AddMicrosoftIdentityMessageHandler(section);
// Assert
var serviceProvider = services.BuildServiceProvider();
@@ -306,6 +405,7 @@ public void AddMicrosoftIdentityMessageHandler_WithConfiguration_EmptyConfigurat
var client = httpClientFactory.CreateClient("TestClient");
Assert.NotNull(client);
+ Assert.Same(builder, result);
}
[Fact]