Skip to content

Commit fc240c7

Browse files
github-actions[bot]priyankatiwari08Copilot
authored
[6.1.8 Cherry-pick] Improve WAM authentication diagnostics for windowless hosts (#4918)
* Cherry-pick of #4858 requires manual resolution To resolve, run: git cherry-pick a62aad4 * [6.1.8] Improve WAM authentication diagnostics for windowless hosts (#4858) Manual port of a62aad4 to release/6.1, where the provider lives in the core driver. - Catch MSAL window_handle_required for WAM interactive auth on Windows and rethrow an MsalClientException with the same error code and actionable guidance. - Document windowless-host alternatives in the provider and options snippets. - Add WamBrokerErrorTests and SqlAuthenticationProviderCollection.Name. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: ec369fd4-31ce-48fd-94fe-dc893a47a803 --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Priyanka Tiwari <prtiwar@microsoft.com> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: ec369fd4-31ce-48fd-94fe-dc893a47a803
1 parent 2a71f00 commit fc240c7

7 files changed

Lines changed: 208 additions & 19 deletions

File tree

‎doc/snippets/Microsoft.Data.SqlClient/ActiveDirectoryAuthenticationProvider.xml‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,15 @@
139139
</summary>
140140
<remarks>
141141
Mandatory to be set only on Android. See https://aka.ms/msal-net-android-activity for further documentation and details.
142+
<para>
143+
A worker process can lack a console window even when it runs on an interactive desktop, for example in the Azure Functions local host.
144+
If no valid parent window is available and WAM requires interactive sign-in, authentication fails with guidance on supported alternatives.
145+
Use <c>Authentication=Active Directory Default</c> with a configured non-interactive credential for windowless hosts.
146+
To use interactive authentication without WAM, supply a custom
147+
<see cref="P:Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProviderOptions.ApplicationClientId"/> and set
148+
<see cref="P:Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProviderOptions.UseWamBroker"/> to <see langword="false"/>.
149+
WAM cannot be disabled for SqlClient's first-party application ID.
150+
</para>
142151
</remarks>
143152
</SetParentActivityOrWindowFunc>
144153
<SetIWin32WindowFunc>

‎doc/snippets/Microsoft.Data.SqlClient/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/src/Microsoft/Data/SqlClient/ActiveDirectoryAuthenticationProvider.cs‎

Lines changed: 49 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ public sealed partial class ActiveDirectoryAuthenticationProvider : SqlAuthentic
2727
/// The purpose of this cache is to allow re-use of Access Tokens fetched for a user interactively or with any other mode
2828
/// to avoid interactive authentication request every-time, within application scope making use of MSAL's userTokenCache.
2929
/// </summary>
30-
private static readonly ConcurrentDictionary<PublicClientAppKey, IPublicClientApplication> s_pcaMap = new();
30+
// Internal for test access.
31+
internal static readonly ConcurrentDictionary<PublicClientAppKey, IPublicClientApplication> s_pcaMap = new();
3132
private static readonly ConcurrentDictionary<TokenCredentialKey, TokenCredentialData> s_tokenCredentialMap = new();
3233
private static SemaphoreSlim s_pcaMapModifierSemaphore = new(1, 1);
3334
private static SemaphoreSlim s_tokenCredentialMapModifierSemaphore = new(1, 1);
@@ -38,6 +39,24 @@ public sealed partial class ActiveDirectoryAuthenticationProvider : SqlAuthentic
3839
// expects the suffix to match the client id of the registered application.
3940
private const string s_wamBrokerRedirectUriPrefix = "ms-appx-web://microsoft.aad.brokerplugin/";
4041

42+
// MSAL error code raised by the Windows broker when no parent window handle is available.
43+
// MSAL does not expose a public constant for this value.
44+
internal const string WindowHandleRequiredErrorCode = "window_handle_required";
45+
46+
internal static MsalClientException CreateWindowHandleRequiredException(MsalClientException ex)
47+
{
48+
// TODO: Localize this message: https://github.com/dotnet/SqlClient/issues/4904
49+
return new MsalClientException(
50+
ex.ErrorCode,
51+
"Active Directory Interactive authentication with Windows Web Account Manager (WAM) requires a valid parent window handle. " +
52+
"Supply an application-owned window handle using ActiveDirectoryAuthenticationProvider.SetParentActivityOrWindowFunc. " +
53+
"For windowless hosts, such as Azure Functions local workers, use Authentication=Active Directory Default with a configured non-interactive credential. " +
54+
"To use interactive authentication without WAM, provide your own ApplicationClientId and set UseWamBroker=false. " +
55+
"WAM cannot be disabled for SqlClient's first-party application ID. " +
56+
ex.Message,
57+
ex);
58+
}
59+
4160
#if NETFRAMEWORK
4261
// Non-broker redirect URI used on .NET Framework when WAM is not in use (legacy embedded
4362
// WebView path).
@@ -367,23 +386,37 @@ previousPw is byte[] previousPwBytes &&
367386
{
368387
try
369388
{
370-
result = await TryAcquireTokenSilent(app, parameters, scopes, cts).ConfigureAwait(false);
371-
SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token (silent) for {0} auth mode. Expiry Time: {1}", parameters.AuthenticationMethod, result?.ExpiresOn);
372-
}
373-
catch (MsalUiRequiredException)
374-
{
375-
// An 'MsalUiRequiredException' is thrown in the case where an interaction is required with the end user of the application,
376-
// for instance, if no refresh token was in the cache, or the user needs to consent, or re-sign-in (for instance if the password expired),
377-
// or the user needs to perform two factor authentication.
378-
result = await AcquireTokenInteractiveDeviceFlowAsync(app, scopes, parameters.ConnectionId, parameters.UserId, parameters.AuthenticationMethod, cts, _customWebUI, _deviceCodeFlowCallback).ConfigureAwait(false);
379-
SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token (interactive) for {0} auth mode. Expiry Time: {1}", parameters.AuthenticationMethod, result?.ExpiresOn);
380-
}
389+
try
390+
{
391+
result = await TryAcquireTokenSilent(app, parameters, scopes, cts).ConfigureAwait(false);
392+
SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token (silent) for {0} auth mode. Expiry Time: {1}", parameters.AuthenticationMethod, result?.ExpiresOn);
393+
}
394+
catch (MsalUiRequiredException)
395+
{
396+
// An 'MsalUiRequiredException' is thrown in the case where an interaction is required with the end user of the application,
397+
// for instance, if no refresh token was in the cache, or the user needs to consent, or re-sign-in (for instance if the password expired),
398+
// or the user needs to perform two factor authentication.
399+
result = await AcquireTokenInteractiveDeviceFlowAsync(app, scopes, parameters.ConnectionId, parameters.UserId, parameters.AuthenticationMethod, cts, _customWebUI, _deviceCodeFlowCallback).ConfigureAwait(false);
400+
SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token (interactive) for {0} auth mode. Expiry Time: {1}", parameters.AuthenticationMethod, result?.ExpiresOn);
401+
}
381402

382-
if (result == null)
403+
if (result == null)
404+
{
405+
// If no existing 'account' is found, we request user to sign in interactively.
406+
result = await AcquireTokenInteractiveDeviceFlowAsync(app, scopes, parameters.ConnectionId, parameters.UserId, parameters.AuthenticationMethod, cts, _customWebUI, _deviceCodeFlowCallback).ConfigureAwait(false);
407+
SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token (interactive) for {0} auth mode. Expiry Time: {1}", parameters.AuthenticationMethod, result?.ExpiresOn);
408+
}
409+
}
410+
// MSAL raises window_handle_required only on Windows, where WAM needs a parent window.
411+
// If WAM support is added for other platforms, revisit this filter and message.
412+
catch (MsalClientException ex) when (
413+
parameters.AuthenticationMethod == SqlAuthenticationMethod.ActiveDirectoryInteractive &&
414+
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
415+
_useWamBroker &&
416+
ex.ErrorCode == WindowHandleRequiredErrorCode)
383417
{
384-
// If no existing 'account' is found, we request user to sign in interactively.
385-
result = await AcquireTokenInteractiveDeviceFlowAsync(app, scopes, parameters.ConnectionId, parameters.UserId, parameters.AuthenticationMethod, cts, _customWebUI, _deviceCodeFlowCallback).ConfigureAwait(false);
386-
SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | Acquired access token (interactive) for {0} auth mode. Expiry Time: {1}", parameters.AuthenticationMethod, result?.ExpiresOn);
418+
SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | WAM interactive authentication requires a valid parent window handle.");
419+
throw CreateWindowHandleRequiredException(ex);
387420
}
388421
}
389422
else

‎src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/AuthorityParsingTests.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ namespace Microsoft.Data.SqlClient.UnitTests.Microsoft.Data.SqlClient
1616
/// The cases below only cover authority shapes that Entra ID actually documents:
1717
/// https://learn.microsoft.com/entra/identity-platform/authentication-national-cloud
1818
/// </remarks>
19-
[Collection("SqlAuthenticationProvider")]
19+
[Collection(SqlAuthenticationProviderCollection.Name)]
2020
public class AuthorityParsingTests
2121
{
2222
private const string Tenant = "72f988bf-86f1-41af-91ab-2d7cd011db47";

‎src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/SqlAuthenticationProviderCollection.cs‎

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

‎src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/WamBrokerTests.cs‎

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

1010
namespace Microsoft.Data.SqlClient.UnitTests.Microsoft.Data.SqlClient
1111
{
12-
[Collection("SqlAuthenticationProvider")]
12+
[Collection(SqlAuthenticationProviderCollection.Name)]
1313
public class WamBrokerTests
1414
{
1515
// The SqlClient first-party application client id that is hard-coded in the provider.

0 commit comments

Comments
 (0)