Skip to content

Commit 4745f32

Browse files
github-actions[bot]priyankatiwari08Copilotmdaigle
authored
Improve WAM authentication diagnostics for windowless hosts (#4858) (#4917)
* Improve WAM missing-window authentication diagnostics Preserve broker requirements while explaining supported authentication alternatives for windowless hosts. Add exception translation regression tests, sync/async integration coverage, and documentation. * Isolate shared MSAL client cache in windowless interactive test Clear the cached public client applications before and after the windowless test so its zero-window callback is neither bypassed by an earlier cached client nor leaked into later interactive tests. Serialize ActiveDirectoryInteractiveTests with the other provider-mutating tests. * Address review feedback on WAM missing-window diagnostics - Revert sample to the constructor available in the referenced Extensions.Azure package. - Add SqlAuthenticationProviderCollection.Name and use it in Azure tests. - Make s_pcaMap internal and remove reflection from WamBrokerErrorTests. - Add localization TODO (#4904) and a note on the Windows-only filter. --------- Co-authored-by: priyankatiwari08 <prtiwar@microsoft.com> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Malcolm Daigle <mdaigle@microsoft.com> Copilot-Session: ec369fd4-31ce-48fd-94fe-dc893a47a803
1 parent 5ba8dfb commit 4745f32

11 files changed

Lines changed: 283 additions & 5 deletions

‎src/Microsoft.Data.SqlClient.Extensions/Azure/doc/ActiveDirectoryAuthenticationProvider.xml‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,15 @@ See the LICENSE file in the project root for more information.
167167
On non-Windows platforms, this callback is forwarded to MSAL so interactive flows can parent their UI to the host Activity / UIViewController (or platform equivalent).
168168

169169
Exceptions thrown by <paramref name="parentActivityOrWindowFunc" /> when it is invoked by MSAL are not caught by the provider; they propagate up to the caller of the originating <c>AcquireToken</c> request so that bugs in the callback surface where they are most diagnosable.
170+
<para>
171+
A worker process can lack a console window even when it runs on an interactive desktop, for example in the Azure Functions local host.
172+
If no valid parent window is available and WAM requires interactive sign-in, authentication fails with guidance on supported alternatives.
173+
Use <c>Authentication=Active Directory Default</c> with a configured non-interactive credential for windowless hosts.
174+
To use interactive authentication without WAM, supply a custom
175+
<see cref="P:Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProviderOptions.ApplicationClientId"/> and set
176+
<see cref="P:Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProviderOptions.UseWamBroker"/> to <see langword="false"/>.
177+
WAM cannot be disabled for SqlClient's first-party application ID.
178+
</para>
170179
</remarks>
171180
</SetParentActivityOrWindowFunc>
172181
<SetIWin32WindowFunc>

‎src/Microsoft.Data.SqlClient.Extensions/Azure/doc/ActiveDirectoryAuthenticationProviderOptions.xml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,14 @@
2929
Defaults to <see langword="false"/> when you provide a custom <see cref="ApplicationClientId"/>.
3030
Otherwise, WAM broker mode is used automatically on Windows.
3131
</summary>
32+
<remarks>
33+
Setting this property to <see langword="false"/> does not disable WAM for SqlClient's first-party application ID,
34+
including when that ID is supplied explicitly. Disabling WAM requires a custom application registration.
35+
WAM interactive authentication requires a valid parent window handle. Applications with a window can supply
36+
its handle using <see cref="M:Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProvider.SetParentActivityOrWindowFunc(System.Func{System.Object})"/>.
37+
Windowless hosts should use a non-interactive credential with <c>Authentication=Active Directory Default</c>,
38+
or use their own application registration with WAM disabled if interactive sign-in is required.
39+
</remarks>
3240
</UseWamBroker>
3341
</members>
3442
</docs>

‎src/Microsoft.Data.SqlClient.Extensions/Azure/src/ActiveDirectoryAuthenticationProvider.cs‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ public sealed partial class ActiveDirectoryAuthenticationProvider : SqlAuthentic
2525
/// The purpose of this cache is to allow re-use of Access Tokens fetched for a user interactively or with any other mode
2626
/// to avoid interactive authentication request every-time, within application scope making use of MSAL's userTokenCache.
2727
/// </summary>
28-
private static readonly ConcurrentDictionary<PublicClientAppKey, IPublicClientApplication> s_pcaMap = new();
28+
// Internal for test access.
29+
internal static readonly ConcurrentDictionary<PublicClientAppKey, IPublicClientApplication> s_pcaMap = new();
2930
private static readonly ConcurrentDictionary<TokenCredentialKey, TokenCredentialData> s_tokenCredentialMap = new();
3031
private static readonly SemaphoreSlim s_pcaMapModifierSemaphore = new(1, 1);
3132
private static readonly SemaphoreSlim s_tokenCredentialMapModifierSemaphore = new(1, 1);
@@ -449,6 +450,30 @@ previousPw is byte[] previousPwBytes &&
449450
// Already shaped for the caller; don't re-wrap it below.
450451
throw;
451452
}
453+
// MSAL raises window_handle_required only on Windows, where WAM needs a parent window.
454+
// If WAM support is added for other platforms, revisit this filter and message.
455+
catch (MsalClientException ex) when (
456+
parameters.AuthenticationMethod == SqlAuthenticationMethod.ActiveDirectoryInteractive &&
457+
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
458+
_useWamBroker &&
459+
ex.ErrorCode == "window_handle_required")
460+
{
461+
SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | WAM interactive authentication requires a valid parent window handle.");
462+
463+
// TODO: Localize this message: https://github.com/dotnet/SqlClient/issues/4904
464+
throw new Extensions.Azure.AuthenticationException(
465+
parameters.AuthenticationMethod,
466+
ex.ErrorCode,
467+
shouldRetry: false,
468+
retryPeriod: 0,
469+
"Active Directory Interactive authentication with Windows Web Account Manager (WAM) requires a valid parent window handle. " +
470+
"Supply an application-owned window handle using ActiveDirectoryAuthenticationProvider.SetParentActivityOrWindowFunc. " +
471+
"For windowless hosts, such as Azure Functions local workers, use Authentication=Active Directory Default with a configured non-interactive credential. " +
472+
"To use interactive authentication without WAM, provide your own ApplicationClientId and set UseWamBroker=false. " +
473+
"WAM cannot be disabled for SqlClient's first-party application ID. " +
474+
ex.Message,
475+
ex);
476+
}
452477
catch (MsalException ex)
453478
{
454479
// Check for an explicitly retryable error.

‎src/Microsoft.Data.SqlClient.Extensions/Azure/src/PackageReadme.md‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,33 @@ await connection.OpenAsync();
127127
| Azure CLI | `AzureCliCredential` | Local development |
128128
| Visual Studio | `VisualStudioCredential` | Development in Visual Studio |
129129

130+
### Interactive authentication in windowless Windows hosts
131+
132+
On Windows, `Authentication=Active Directory Interactive` uses Web Account Manager
133+
(WAM) with SqlClient's built-in Microsoft application ID. WAM requires a valid
134+
parent window handle when interactive sign-in is needed. A local Azure Functions
135+
worker can lack a console window even when its developer is using an interactive
136+
desktop.
137+
138+
For windowless local development, use `Authentication=Active Directory Default`
139+
with a configured developer credential, such as an Azure CLI or Visual Studio
140+
sign-in. For Azure-hosted Functions, prefer managed identity.
141+
142+
If the application owns a suitable window, supply its handle through
143+
`ActiveDirectoryAuthenticationProvider.SetParentActivityOrWindowFunc` before
144+
opening connections. Do not use an unrelated application's window.
145+
146+
If interactive sign-in without WAM is required, register your own Entra application
147+
and supply its client ID with `UseWamBroker = false`. Setting `UseWamBroker = false`
148+
alone does **not** disable WAM for SqlClient's first-party application ID.
149+
On modern .NET, configure a public client/native redirect URI of `http://localhost`
150+
for system-browser authentication and the Azure SQL Database delegated
151+
`user_impersonation` permission, with consent as required by your tenant. The signed-in
152+
user must also have database access.
153+
154+
See the [custom application ID sample](https://github.com/dotnet/SqlClient/blob/main/doc/samples/ApplicationClientIdAzureAuthenticationProvider.cs)
155+
and the [MSAL parent window requirements](https://learn.microsoft.com/entra/msal/dotnet/acquiring-tokens/desktop-mobile/wam#parent-window-handles).
156+
130157
## Documentation
131158

132159
- [Entra ID Authentication](https://learn.microsoft.com/azure/azure-sql/database/authentication-aad-overview)

‎src/Microsoft.Data.SqlClient.Extensions/Azure/test/AADAuthenticationTests.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
namespace Microsoft.Data.SqlClient.Extensions.Azure.Test;
1111

1212
// These tests were moved from MDS FunctionalTests AADAuthenticationTests.cs.
13-
[Collection("SqlAuthenticationProvider")]
13+
[Collection(SqlAuthenticationProviderCollection.Name)]
1414
public class AADAuthenticationTests
1515
{
1616
[Fact]

‎src/Microsoft.Data.SqlClient.Extensions/Azure/test/ActiveDirectoryInteractiveTests.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
namespace Microsoft.Data.SqlClient.Extensions.Azure.Test;
88

9+
[Collection(SqlAuthenticationProviderCollection.Name)]
910
public class ActiveDirectoryInteractiveTests
1011
{
1112
private readonly ITestOutputHelper _output;

‎src/Microsoft.Data.SqlClient.Extensions/Azure/test/DefaultAuthProviderTests.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
namespace Microsoft.Data.SqlClient.Extensions.Azure.Test;
66

7-
[Collection("SqlAuthenticationProvider")]
7+
[Collection(SqlAuthenticationProviderCollection.Name)]
88
public class DefaultAuthProviderTests
99
{
1010
// Verify that our auth provider has been installed for all AAD/Entra

‎src/Microsoft.Data.SqlClient.Extensions/Azure/test/SqlAuthenticationProviderCollection.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ namespace Microsoft.Data.SqlClient.Extensions.Azure.Test;
88
/// Defines a test collection that serializes execution of test classes
99
/// which mutate the global <see cref="SqlAuthenticationProvider"/> registry.
1010
/// </summary>
11-
[CollectionDefinition("SqlAuthenticationProvider")]
11+
[CollectionDefinition(Name)]
1212
public class SqlAuthenticationProviderCollection
1313
{
14+
public const string Name = "SqlAuthenticationProvider";
1415
}
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
using System.Runtime.InteropServices;
6+
using Microsoft.Identity.Client;
7+
8+
namespace Microsoft.Data.SqlClient.Extensions.Azure.Test;
9+
10+
/// <summary>
11+
/// Verifies missing-window diagnostics without opening UI or contacting Entra ID.
12+
/// </summary>
13+
[Collection(SqlAuthenticationProviderCollection.Name)]
14+
public class WamBrokerErrorTests
15+
{
16+
/// <summary>
17+
/// Both first-party and custom applications using WAM receive actionable guidance on Windows.
18+
/// Other platforms retain the original MSAL diagnostic.
19+
/// </summary>
20+
[Theory]
21+
[InlineData(null)]
22+
[InlineData("11111111-2222-3333-4444-555555555555")]
23+
public async Task AcquireTokenAsync_MissingWamWindow_ExplainsSupportedAlternatives(string? applicationClientId)
24+
{
25+
var provider = new ActiveDirectoryAuthenticationProvider(
26+
new ActiveDirectoryAuthenticationProviderOptions
27+
{
28+
ApplicationClientId = applicationClientId,
29+
UseWamBroker = true,
30+
});
31+
provider.SetParentActivityOrWindowFunc(
32+
() => throw new InvalidOperationException("Window discovery must not precede MSAL token acquisition."));
33+
var cause = new MsalClientException("window_handle_required", "Original MSAL diagnostic.");
34+
35+
AuthenticationException exception = await AcquireWithMsalExceptionAsync(
36+
provider, SqlAuthenticationMethod.ActiveDirectoryInteractive, cause);
37+
38+
Assert.Equal(SqlAuthenticationMethod.ActiveDirectoryInteractive, exception.Method);
39+
Assert.Equal(cause.ErrorCode, exception.FailureCode);
40+
Assert.Same(cause, exception.InnerException);
41+
Assert.False(exception.ShouldRetry);
42+
Assert.Equal(0, exception.RetryPeriod);
43+
Assert.Contains(cause.Message, exception.Message);
44+
45+
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
46+
{
47+
Assert.Contains("parent window handle", exception.Message);
48+
Assert.Contains("SetParentActivityOrWindowFunc", exception.Message);
49+
Assert.Contains("Active Directory Default", exception.Message);
50+
Assert.Contains("ApplicationClientId", exception.Message);
51+
Assert.Contains("UseWamBroker", exception.Message);
52+
Assert.Contains("first-party", exception.Message);
53+
}
54+
else
55+
{
56+
Assert.Equal($"Failed to acquire access token for {exception.Method}: {cause.Message}", exception.Message);
57+
}
58+
}
59+
60+
/// <summary>
61+
/// Non-broker flows, other authentication methods, and unrelated MSAL failures are not
62+
/// relabeled as missing WAM windows.
63+
/// </summary>
64+
[Theory]
65+
[InlineData(SqlAuthenticationMethod.ActiveDirectoryInteractive, false, "window_handle_required")]
66+
[InlineData(SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow, true, "window_handle_required")]
67+
[InlineData(SqlAuthenticationMethod.ActiveDirectoryIntegrated, true, "window_handle_required")]
68+
[InlineData(SqlAuthenticationMethod.ActiveDirectoryInteractive, true, "authentication_canceled")]
69+
public async Task AcquireTokenAsync_OtherMsalFailures_PreservesDiagnostic(
70+
SqlAuthenticationMethod method, bool useWamBroker, string errorCode)
71+
{
72+
var provider = new ActiveDirectoryAuthenticationProvider(
73+
new ActiveDirectoryAuthenticationProviderOptions
74+
{
75+
ApplicationClientId = "11111111-2222-3333-4444-555555555555",
76+
UseWamBroker = useWamBroker,
77+
});
78+
var cause = new MsalClientException(errorCode, "Original MSAL diagnostic.");
79+
80+
AuthenticationException exception = await AcquireWithMsalExceptionAsync(provider, method, cause);
81+
82+
Assert.Equal(method, exception.Method);
83+
Assert.Equal(errorCode, exception.FailureCode);
84+
Assert.Same(cause, exception.InnerException);
85+
Assert.False(exception.ShouldRetry);
86+
Assert.Equal($"Failed to acquire access token for {method}: {cause.Message}", exception.Message);
87+
}
88+
89+
/// <summary>
90+
/// Installs an isolated MSAL client whose cache callback throws the supplied exception,
91+
/// exercising the provider's real exception translation without a network request.
92+
/// The cache entry is removed even if an assertion fails.
93+
/// </summary>
94+
/// <param name="provider">The provider configuration under test.</param>
95+
/// <param name="method">The authentication method under test.</param>
96+
/// <param name="cause">The MSAL failure to propagate through token acquisition.</param>
97+
/// <returns>The translated authentication failure.</returns>
98+
private static async Task<AuthenticationException> AcquireWithMsalExceptionAsync(
99+
ActiveDirectoryAuthenticationProvider provider, SqlAuthenticationMethod method, MsalClientException cause)
100+
{
101+
string authority = $"https://login.microsoftonline.com/{Guid.NewGuid()}";
102+
string redirectUri = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
103+
? provider.UseWamBroker
104+
? $"ms-appx-web://microsoft.aad.brokerplugin/{provider.ApplicationClientId}"
105+
#if NETFRAMEWORK
106+
: "https://login.microsoftonline.com/common/oauth2/nativeclient"
107+
#else
108+
: "http://localhost"
109+
#endif
110+
: "http://localhost";
111+
112+
var key = new ActiveDirectoryAuthenticationProvider.PublicClientAppKey(
113+
authority, redirectUri, provider.ApplicationClientId
114+
#if NETFRAMEWORK
115+
, null
116+
#endif
117+
);
118+
IPublicClientApplication app = PublicClientApplicationBuilder.Create(provider.ApplicationClientId)
119+
.WithAuthority(authority)
120+
.WithRedirectUri(redirectUri)
121+
.Build();
122+
app.UserTokenCache.SetBeforeAccess(_ => throw cause);
123+
124+
var cache = ActiveDirectoryAuthenticationProvider.s_pcaMap;
125+
Assert.True(cache.TryAdd(key, app));
126+
try
127+
{
128+
var parameters = new SqlAuthenticationParameters(
129+
method, "test-server", "test-database", "https://database.windows.net/",
130+
authority, userId: null, password: null, connectionId: Guid.NewGuid(), connectionTimeout: 30);
131+
return await Assert.ThrowsAsync<AuthenticationException>(() => provider.AcquireTokenAsync(parameters));
132+
}
133+
finally
134+
{
135+
cache.TryRemove(key, out _);
136+
}
137+
}
138+
}

‎src/Microsoft.Data.SqlClient.Extensions/Azure/test/WamBrokerTests.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
namespace Microsoft.Data.SqlClient.Extensions.Azure.Test;
88

9-
[Collection("SqlAuthenticationProvider")]
9+
[Collection(SqlAuthenticationProviderCollection.Name)]
1010
public class WamBrokerTests
1111
{
1212
// The SqlClient first-party application client id that is hard-coded in the provider.

0 commit comments

Comments
 (0)