From 0b871eef9208c67db504477c71b267c05134ab0d Mon Sep 17 00:00:00 2001 From: Priyanka Tiwari Date: Mon, 19 Oct 2026 21:42:40 +0530 Subject: [PATCH 1/3] 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. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: ec369fd4-31ce-48fd-94fe-dc893a47a803 --- ...tionClientIdAzureAuthenticationProvider.cs | 9 +- .../ActiveDirectoryAuthenticationProvider.xml | 9 ++ ...DirectoryAuthenticationProviderOptions.xml | 8 + .../ActiveDirectoryAuthenticationProvider.cs | 21 +++ .../Azure/src/PackageReadme.md | 27 ++++ .../Azure/test/WamBrokerErrorTests.cs | 144 ++++++++++++++++++ .../WindowlessInteractiveConnectionTests.cs | 59 +++++++ 7 files changed, 275 insertions(+), 2 deletions(-) create mode 100644 src/Microsoft.Data.SqlClient.Extensions/Azure/test/WamBrokerErrorTests.cs create mode 100644 src/Microsoft.Data.SqlClient.Extensions/Azure/test/WindowlessInteractiveConnectionTests.cs diff --git a/doc/samples/ApplicationClientIdAzureAuthenticationProvider.cs b/doc/samples/ApplicationClientIdAzureAuthenticationProvider.cs index cbc5c1a38b..c7672028de 100644 --- a/doc/samples/ApplicationClientIdAzureAuthenticationProvider.cs +++ b/doc/samples/ApplicationClientIdAzureAuthenticationProvider.cs @@ -8,8 +8,13 @@ public class Program { public static void Main() { - // Supported for all authentication modes supported by ActiveDirectoryAuthenticationProvider - ActiveDirectoryAuthenticationProvider provider = new ActiveDirectoryAuthenticationProvider(""); + // Disabling WAM requires your own app registration, not SqlClient's first-party app ID. + ActiveDirectoryAuthenticationProvider provider = new ActiveDirectoryAuthenticationProvider( + new ActiveDirectoryAuthenticationProviderOptions + { + ApplicationClientId = "", + UseWamBroker = false + }); if (provider.IsSupported(SqlAuthenticationMethod.ActiveDirectoryInteractive)) { SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, provider); diff --git a/src/Microsoft.Data.SqlClient.Extensions/Azure/doc/ActiveDirectoryAuthenticationProvider.xml b/src/Microsoft.Data.SqlClient.Extensions/Azure/doc/ActiveDirectoryAuthenticationProvider.xml index 2b58a8676f..93de183fac 100644 --- a/src/Microsoft.Data.SqlClient.Extensions/Azure/doc/ActiveDirectoryAuthenticationProvider.xml +++ b/src/Microsoft.Data.SqlClient.Extensions/Azure/doc/ActiveDirectoryAuthenticationProvider.xml @@ -167,6 +167,15 @@ See the LICENSE file in the project root for more information. 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). Exceptions thrown by when it is invoked by MSAL are not caught by the provider; they propagate up to the caller of the originating AcquireToken request so that bugs in the callback surface where they are most diagnosable. + + A worker process can lack a console window even when it runs on an interactive desktop, for example in the Azure Functions local host. + If no valid parent window is available and WAM requires interactive sign-in, authentication fails with guidance on supported alternatives. + Use Authentication=Active Directory Default with a configured non-interactive credential for windowless hosts. + To use interactive authentication without WAM, supply a custom + and set + to . + WAM cannot be disabled for SqlClient's first-party application ID. + diff --git a/src/Microsoft.Data.SqlClient.Extensions/Azure/doc/ActiveDirectoryAuthenticationProviderOptions.xml b/src/Microsoft.Data.SqlClient.Extensions/Azure/doc/ActiveDirectoryAuthenticationProviderOptions.xml index c290947adb..2def8bce99 100644 --- a/src/Microsoft.Data.SqlClient.Extensions/Azure/doc/ActiveDirectoryAuthenticationProviderOptions.xml +++ b/src/Microsoft.Data.SqlClient.Extensions/Azure/doc/ActiveDirectoryAuthenticationProviderOptions.xml @@ -29,6 +29,14 @@ Defaults to when you provide a custom . Otherwise, WAM broker mode is used automatically on Windows. + + Setting this property to does not disable WAM for SqlClient's first-party application ID, + including when that ID is supplied explicitly. Disabling WAM requires a custom application registration. + WAM interactive authentication requires a valid parent window handle. Applications with a window can supply + its handle using . + Windowless hosts should use a non-interactive credential with Authentication=Active Directory Default, + or use their own application registration with WAM disabled if interactive sign-in is required. + \ No newline at end of file diff --git a/src/Microsoft.Data.SqlClient.Extensions/Azure/src/ActiveDirectoryAuthenticationProvider.cs b/src/Microsoft.Data.SqlClient.Extensions/Azure/src/ActiveDirectoryAuthenticationProvider.cs index cbb0371bec..90f7f73c03 100644 --- a/src/Microsoft.Data.SqlClient.Extensions/Azure/src/ActiveDirectoryAuthenticationProvider.cs +++ b/src/Microsoft.Data.SqlClient.Extensions/Azure/src/ActiveDirectoryAuthenticationProvider.cs @@ -449,6 +449,27 @@ previousPw is byte[] previousPwBytes && // Already shaped for the caller; don't re-wrap it below. throw; } + catch (MsalClientException ex) when ( + parameters.AuthenticationMethod == SqlAuthenticationMethod.ActiveDirectoryInteractive && + RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && + _useWamBroker && + ex.ErrorCode == "window_handle_required") + { + SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | WAM interactive authentication requires a valid parent window handle."); + + throw new Extensions.Azure.AuthenticationException( + parameters.AuthenticationMethod, + ex.ErrorCode, + shouldRetry: false, + retryPeriod: 0, + "Active Directory Interactive authentication with Windows Web Account Manager (WAM) requires a valid parent window handle. " + + "Supply an application-owned window handle using ActiveDirectoryAuthenticationProvider.SetParentActivityOrWindowFunc. " + + "For windowless hosts, such as Azure Functions local workers, use Authentication=Active Directory Default with a configured non-interactive credential. " + + "To use interactive authentication without WAM, provide your own ApplicationClientId and set UseWamBroker=false. " + + "WAM cannot be disabled for SqlClient's first-party application ID. " + + ex.Message, + ex); + } catch (MsalException ex) { // Check for an explicitly retryable error. diff --git a/src/Microsoft.Data.SqlClient.Extensions/Azure/src/PackageReadme.md b/src/Microsoft.Data.SqlClient.Extensions/Azure/src/PackageReadme.md index 0c19fedf86..990cd3890c 100644 --- a/src/Microsoft.Data.SqlClient.Extensions/Azure/src/PackageReadme.md +++ b/src/Microsoft.Data.SqlClient.Extensions/Azure/src/PackageReadme.md @@ -146,6 +146,33 @@ await connection.OpenAsync(); | Azure CLI | `AzureCliCredential` | Local development | | Visual Studio | `VisualStudioCredential` | Development in Visual Studio | +### Interactive authentication in windowless Windows hosts + +On Windows, `Authentication=Active Directory Interactive` uses Web Account Manager +(WAM) with SqlClient's built-in Microsoft application ID. WAM requires a valid +parent window handle when interactive sign-in is needed. A local Azure Functions +worker can lack a console window even when its developer is using an interactive +desktop. + +For windowless local development, use `Authentication=Active Directory Default` +with a configured developer credential, such as an Azure CLI or Visual Studio +sign-in. For Azure-hosted Functions, prefer managed identity. + +If the application owns a suitable window, supply its handle through +`ActiveDirectoryAuthenticationProvider.SetParentActivityOrWindowFunc` before +opening connections. Do not use an unrelated application's window. + +If interactive sign-in without WAM is required, register your own Entra application +and supply its client ID with `UseWamBroker = false`. Setting `UseWamBroker = false` +alone does **not** disable WAM for SqlClient's first-party application ID. +On modern .NET, configure a public client/native redirect URI of `http://localhost` +for system-browser authentication and the Azure SQL Database delegated +`user_impersonation` permission, with consent as required by your tenant. The signed-in +user must also have database access. + +See the [custom application ID sample](https://github.com/dotnet/SqlClient/blob/main/doc/samples/ApplicationClientIdAzureAuthenticationProvider.cs) +and the [MSAL parent window requirements](https://learn.microsoft.com/entra/msal/dotnet/acquiring-tokens/desktop-mobile/wam#parent-window-handles). + ## Documentation - [Entra ID Authentication](https://learn.microsoft.com/azure/azure-sql/database/authentication-aad-overview) diff --git a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WamBrokerErrorTests.cs b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WamBrokerErrorTests.cs new file mode 100644 index 0000000000..7eddcba3e1 --- /dev/null +++ b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WamBrokerErrorTests.cs @@ -0,0 +1,144 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Concurrent; +using System.Reflection; +using System.Runtime.InteropServices; +using Microsoft.Identity.Client; + +namespace Microsoft.Data.SqlClient.Extensions.Azure.Test; + +/// +/// Verifies missing-window diagnostics without opening UI or contacting Entra ID. +/// +[Collection("SqlAuthenticationProvider")] +public class WamBrokerErrorTests +{ + /// + /// Both first-party and custom applications using WAM receive actionable guidance on Windows. + /// Other platforms retain the original MSAL diagnostic. + /// + [Theory] + [InlineData(null)] + [InlineData("11111111-2222-3333-4444-555555555555")] + public async Task AcquireTokenAsync_MissingWamWindow_ExplainsSupportedAlternatives(string? applicationClientId) + { + var provider = new ActiveDirectoryAuthenticationProvider( + new ActiveDirectoryAuthenticationProviderOptions + { + ApplicationClientId = applicationClientId, + UseWamBroker = true, + }); + provider.SetParentActivityOrWindowFunc( + () => throw new InvalidOperationException("Window discovery must not precede MSAL token acquisition.")); + var cause = new MsalClientException("window_handle_required", "Original MSAL diagnostic."); + + AuthenticationException exception = await AcquireWithMsalExceptionAsync( + provider, SqlAuthenticationMethod.ActiveDirectoryInteractive, cause); + + Assert.Equal(SqlAuthenticationMethod.ActiveDirectoryInteractive, exception.Method); + Assert.Equal(cause.ErrorCode, exception.FailureCode); + Assert.Same(cause, exception.InnerException); + Assert.False(exception.ShouldRetry); + Assert.Equal(0, exception.RetryPeriod); + Assert.Contains(cause.Message, exception.Message); + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + Assert.Contains("parent window handle", exception.Message); + Assert.Contains("SetParentActivityOrWindowFunc", exception.Message); + Assert.Contains("Active Directory Default", exception.Message); + Assert.Contains("ApplicationClientId", exception.Message); + Assert.Contains("UseWamBroker", exception.Message); + Assert.Contains("first-party", exception.Message); + } + else + { + Assert.Equal($"Failed to acquire access token for {exception.Method}: {cause.Message}", exception.Message); + } + } + + /// + /// Non-broker flows, other authentication methods, and unrelated MSAL failures are not + /// relabeled as missing WAM windows. + /// + [Theory] + [InlineData(SqlAuthenticationMethod.ActiveDirectoryInteractive, false, "window_handle_required")] + [InlineData(SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow, true, "window_handle_required")] + [InlineData(SqlAuthenticationMethod.ActiveDirectoryIntegrated, true, "window_handle_required")] + [InlineData(SqlAuthenticationMethod.ActiveDirectoryInteractive, true, "authentication_canceled")] + public async Task AcquireTokenAsync_OtherMsalFailures_PreservesDiagnostic( + SqlAuthenticationMethod method, bool useWamBroker, string errorCode) + { + var provider = new ActiveDirectoryAuthenticationProvider( + new ActiveDirectoryAuthenticationProviderOptions + { + ApplicationClientId = "11111111-2222-3333-4444-555555555555", + UseWamBroker = useWamBroker, + }); + var cause = new MsalClientException(errorCode, "Original MSAL diagnostic."); + + AuthenticationException exception = await AcquireWithMsalExceptionAsync(provider, method, cause); + + Assert.Equal(method, exception.Method); + Assert.Equal(errorCode, exception.FailureCode); + Assert.Same(cause, exception.InnerException); + Assert.False(exception.ShouldRetry); + Assert.Equal($"Failed to acquire access token for {method}: {cause.Message}", exception.Message); + } + + /// + /// Installs an isolated MSAL client whose cache callback throws the supplied exception, + /// exercising the provider's real exception translation without a network request. + /// The cache entry is removed even if an assertion fails. + /// + /// The provider configuration under test. + /// The authentication method under test. + /// The MSAL failure to propagate through token acquisition. + /// The translated authentication failure. + private static async Task AcquireWithMsalExceptionAsync( + ActiveDirectoryAuthenticationProvider provider, SqlAuthenticationMethod method, MsalClientException cause) + { + string authority = $"https://login.microsoftonline.com/{Guid.NewGuid()}"; + string redirectUri = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) + ? provider.UseWamBroker + ? $"ms-appx-web://microsoft.aad.brokerplugin/{provider.ApplicationClientId}" +#if NETFRAMEWORK + : "https://login.microsoftonline.com/common/oauth2/nativeclient" +#else + : "http://localhost" +#endif + : "http://localhost"; + + var key = new ActiveDirectoryAuthenticationProvider.PublicClientAppKey( + authority, redirectUri, provider.ApplicationClientId +#if NETFRAMEWORK + , null +#endif + ); + IPublicClientApplication app = PublicClientApplicationBuilder.Create(provider.ApplicationClientId) + .WithAuthority(authority) + .WithRedirectUri(redirectUri) + .Build(); + app.UserTokenCache.SetBeforeAccess(_ => throw cause); + + FieldInfo? field = typeof(ActiveDirectoryAuthenticationProvider).GetField( + "s_pcaMap", BindingFlags.Static | BindingFlags.NonPublic); + Assert.NotNull(field); + var cache = Assert.IsType>( + field!.GetValue(null)); + Assert.True(cache.TryAdd(key, app)); + try + { + var parameters = new SqlAuthenticationParameters( + method, "test-server", "test-database", "https://database.windows.net/", + authority, userId: null, password: null, connectionId: Guid.NewGuid(), connectionTimeout: 30); + return await Assert.ThrowsAsync(() => provider.AcquireTokenAsync(parameters)); + } + finally + { + cache.TryRemove(key, out _); + } + } +} diff --git a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WindowlessInteractiveConnectionTests.cs b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WindowlessInteractiveConnectionTests.cs new file mode 100644 index 0000000000..084b553b38 --- /dev/null +++ b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WindowlessInteractiveConnectionTests.cs @@ -0,0 +1,59 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace Microsoft.Data.SqlClient.Extensions.Azure.Test; + +/// +/// Exercises the windowless WAM diagnostic through real Azure SQL login handshakes. +/// +[Collection("SqlAuthenticationProvider")] +public class WindowlessInteractiveConnectionTests +{ + /// + /// Both connection-opening APIs surface the actionable WAM error when no parent window + /// is supplied. A unique login hint prevents reuse of a silently cached account. + /// + [ConditionalTheory(typeof(Config), nameof(Config.OnWindows), nameof(Config.IsAzureSqlConnectionString))] + [Trait("category", "interactive")] + [InlineData(false)] + [InlineData(true)] + public async Task Open_MissingParentWindow_ExplainsSupportedAlternatives(bool async) + { + var builder = new SqlConnectionStringBuilder(Config.TCPConnectionString) + { + Authentication = SqlAuthenticationMethod.ActiveDirectoryInteractive, + IntegratedSecurity = false, + UserID = $"windowless-{Guid.NewGuid():N}@example.invalid", + Pooling = false, + }; + builder.Remove("Password"); + + var provider = new ActiveDirectoryAuthenticationProvider(); + provider.SetParentActivityOrWindowFunc(() => IntPtr.Zero); + SqlAuthenticationProvider? original = + SqlAuthenticationProvider.GetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive); + Assert.NotNull(original); + + try + { + SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, provider); + using var connection = new SqlConnection(builder.ConnectionString); + + SqlException exception = async + ? await Assert.ThrowsAsync(() => connection.OpenAsync()) + : Assert.Throws(() => connection.Open()); + + Assert.Contains("window_handle_required", exception.Message); + Assert.Contains("parent window handle", exception.Message); + Assert.Contains("SetParentActivityOrWindowFunc", exception.Message); + Assert.Contains("Active Directory Default", exception.Message); + Assert.Contains("ApplicationClientId", exception.Message); + Assert.Contains("UseWamBroker", exception.Message); + } + finally + { + SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, original!); + } + } +} From 922c1ef18a11dd50588f00a11c44dfbe3e1d1e30 Mon Sep 17 00:00:00 2001 From: Priyanka Tiwari Date: Mon, 19 Oct 2026 21:59:33 +0530 Subject: [PATCH 2/3] 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. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: ec369fd4-31ce-48fd-94fe-dc893a47a803 --- .../Azure/test/ActiveDirectoryInteractiveTests.cs | 1 + .../Azure/test/WindowlessInteractiveConnectionTests.cs | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/ActiveDirectoryInteractiveTests.cs b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/ActiveDirectoryInteractiveTests.cs index 9f858a4d2b..e819199625 100644 --- a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/ActiveDirectoryInteractiveTests.cs +++ b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/ActiveDirectoryInteractiveTests.cs @@ -6,6 +6,7 @@ namespace Microsoft.Data.SqlClient.Extensions.Azure.Test; +[Collection("SqlAuthenticationProvider")] public class ActiveDirectoryInteractiveTests { private readonly ITestOutputHelper _output; diff --git a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WindowlessInteractiveConnectionTests.cs b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WindowlessInteractiveConnectionTests.cs index 084b553b38..b4bd358d37 100644 --- a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WindowlessInteractiveConnectionTests.cs +++ b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WindowlessInteractiveConnectionTests.cs @@ -35,6 +35,11 @@ public async Task Open_MissingParentWindow_ExplainsSupportedAlternatives(bool as SqlAuthenticationProvider.GetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive); Assert.NotNull(original); + // Cached MSAL clients capture the window callback of the provider that created them, + // and their cache key does not include the provider. Clear the cache so this test uses + // its zero-window callback and does not leave that callback behind for later tests. + ActiveDirectoryAuthenticationProvider.ClearUserTokenCache(); + try { SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, provider); @@ -54,6 +59,7 @@ public async Task Open_MissingParentWindow_ExplainsSupportedAlternatives(bool as finally { SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, original!); + ActiveDirectoryAuthenticationProvider.ClearUserTokenCache(); } } } From e93d8fc03a2aba658c7f7161147d111c8de43115 Mon Sep 17 00:00:00 2001 From: Priyanka Tiwari Date: Thu, 22 Oct 2026 19:14:56 +0530 Subject: [PATCH 3/3] 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: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: ec369fd4-31ce-48fd-94fe-dc893a47a803 --- .../ApplicationClientIdAzureAuthenticationProvider.cs | 9 ++------- .../Azure/src/ActiveDirectoryAuthenticationProvider.cs | 6 +++++- .../Azure/test/AADAuthenticationTests.cs | 2 +- .../Azure/test/ActiveDirectoryInteractiveTests.cs | 2 +- .../Azure/test/DefaultAuthProviderTests.cs | 2 +- .../Azure/test/SqlAuthenticationProviderCollection.cs | 3 ++- .../Azure/test/WamBrokerErrorTests.cs | 10 ++-------- .../Azure/test/WamBrokerTests.cs | 2 +- .../Azure/test/WindowlessInteractiveConnectionTests.cs | 2 +- 9 files changed, 16 insertions(+), 22 deletions(-) diff --git a/doc/samples/ApplicationClientIdAzureAuthenticationProvider.cs b/doc/samples/ApplicationClientIdAzureAuthenticationProvider.cs index c7672028de..cbc5c1a38b 100644 --- a/doc/samples/ApplicationClientIdAzureAuthenticationProvider.cs +++ b/doc/samples/ApplicationClientIdAzureAuthenticationProvider.cs @@ -8,13 +8,8 @@ public class Program { public static void Main() { - // Disabling WAM requires your own app registration, not SqlClient's first-party app ID. - ActiveDirectoryAuthenticationProvider provider = new ActiveDirectoryAuthenticationProvider( - new ActiveDirectoryAuthenticationProviderOptions - { - ApplicationClientId = "", - UseWamBroker = false - }); + // Supported for all authentication modes supported by ActiveDirectoryAuthenticationProvider + ActiveDirectoryAuthenticationProvider provider = new ActiveDirectoryAuthenticationProvider(""); if (provider.IsSupported(SqlAuthenticationMethod.ActiveDirectoryInteractive)) { SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, provider); diff --git a/src/Microsoft.Data.SqlClient.Extensions/Azure/src/ActiveDirectoryAuthenticationProvider.cs b/src/Microsoft.Data.SqlClient.Extensions/Azure/src/ActiveDirectoryAuthenticationProvider.cs index 90f7f73c03..ec4c492ef6 100644 --- a/src/Microsoft.Data.SqlClient.Extensions/Azure/src/ActiveDirectoryAuthenticationProvider.cs +++ b/src/Microsoft.Data.SqlClient.Extensions/Azure/src/ActiveDirectoryAuthenticationProvider.cs @@ -25,7 +25,8 @@ public sealed partial class ActiveDirectoryAuthenticationProvider : SqlAuthentic /// The purpose of this cache is to allow re-use of Access Tokens fetched for a user interactively or with any other mode /// to avoid interactive authentication request every-time, within application scope making use of MSAL's userTokenCache. /// - private static readonly ConcurrentDictionary s_pcaMap = new(); + // Internal for test access. + internal static readonly ConcurrentDictionary s_pcaMap = new(); private static readonly ConcurrentDictionary s_tokenCredentialMap = new(); private static readonly SemaphoreSlim s_pcaMapModifierSemaphore = new(1, 1); private static readonly SemaphoreSlim s_tokenCredentialMapModifierSemaphore = new(1, 1); @@ -449,6 +450,8 @@ previousPw is byte[] previousPwBytes && // Already shaped for the caller; don't re-wrap it below. throw; } + // MSAL raises window_handle_required only on Windows, where WAM needs a parent window. + // If WAM support is added for other platforms, revisit this filter and message. catch (MsalClientException ex) when ( parameters.AuthenticationMethod == SqlAuthenticationMethod.ActiveDirectoryInteractive && RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && @@ -457,6 +460,7 @@ previousPw is byte[] previousPwBytes && { SqlClientEventSource.Log.TryTraceEvent("AcquireTokenAsync | WAM interactive authentication requires a valid parent window handle."); + // TODO: Localize this message: https://github.com/dotnet/SqlClient/issues/4904 throw new Extensions.Azure.AuthenticationException( parameters.AuthenticationMethod, ex.ErrorCode, diff --git a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/AADAuthenticationTests.cs b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/AADAuthenticationTests.cs index e90dcce506..19fd93429c 100644 --- a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/AADAuthenticationTests.cs +++ b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/AADAuthenticationTests.cs @@ -10,7 +10,7 @@ namespace Microsoft.Data.SqlClient.Extensions.Azure.Test; // These tests were moved from MDS FunctionalTests AADAuthenticationTests.cs. -[Collection("SqlAuthenticationProvider")] +[Collection(SqlAuthenticationProviderCollection.Name)] public class AADAuthenticationTests { [Fact] diff --git a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/ActiveDirectoryInteractiveTests.cs b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/ActiveDirectoryInteractiveTests.cs index e819199625..1f6cba0337 100644 --- a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/ActiveDirectoryInteractiveTests.cs +++ b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/ActiveDirectoryInteractiveTests.cs @@ -6,7 +6,7 @@ namespace Microsoft.Data.SqlClient.Extensions.Azure.Test; -[Collection("SqlAuthenticationProvider")] +[Collection(SqlAuthenticationProviderCollection.Name)] public class ActiveDirectoryInteractiveTests { private readonly ITestOutputHelper _output; diff --git a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/DefaultAuthProviderTests.cs b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/DefaultAuthProviderTests.cs index fa426141c9..321c1ae2e4 100644 --- a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/DefaultAuthProviderTests.cs +++ b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/DefaultAuthProviderTests.cs @@ -4,7 +4,7 @@ namespace Microsoft.Data.SqlClient.Extensions.Azure.Test; -[Collection("SqlAuthenticationProvider")] +[Collection(SqlAuthenticationProviderCollection.Name)] public class DefaultAuthProviderTests { // Verify that our auth provider has been installed for all AAD/Entra diff --git a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/SqlAuthenticationProviderCollection.cs b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/SqlAuthenticationProviderCollection.cs index 2bf23f7873..64562b353b 100644 --- a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/SqlAuthenticationProviderCollection.cs +++ b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/SqlAuthenticationProviderCollection.cs @@ -8,7 +8,8 @@ namespace Microsoft.Data.SqlClient.Extensions.Azure.Test; /// Defines a test collection that serializes execution of test classes /// which mutate the global registry. /// -[CollectionDefinition("SqlAuthenticationProvider")] +[CollectionDefinition(Name)] public class SqlAuthenticationProviderCollection { + public const string Name = "SqlAuthenticationProvider"; } diff --git a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WamBrokerErrorTests.cs b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WamBrokerErrorTests.cs index 7eddcba3e1..6d8c4e3cff 100644 --- a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WamBrokerErrorTests.cs +++ b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WamBrokerErrorTests.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Collections.Concurrent; -using System.Reflection; using System.Runtime.InteropServices; using Microsoft.Identity.Client; @@ -12,7 +10,7 @@ namespace Microsoft.Data.SqlClient.Extensions.Azure.Test; /// /// Verifies missing-window diagnostics without opening UI or contacting Entra ID. /// -[Collection("SqlAuthenticationProvider")] +[Collection(SqlAuthenticationProviderCollection.Name)] public class WamBrokerErrorTests { /// @@ -123,11 +121,7 @@ private static async Task AcquireWithMsalExceptionAsync .Build(); app.UserTokenCache.SetBeforeAccess(_ => throw cause); - FieldInfo? field = typeof(ActiveDirectoryAuthenticationProvider).GetField( - "s_pcaMap", BindingFlags.Static | BindingFlags.NonPublic); - Assert.NotNull(field); - var cache = Assert.IsType>( - field!.GetValue(null)); + var cache = ActiveDirectoryAuthenticationProvider.s_pcaMap; Assert.True(cache.TryAdd(key, app)); try { diff --git a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WamBrokerTests.cs b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WamBrokerTests.cs index 9b2aa5dcf7..529653c909 100644 --- a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WamBrokerTests.cs +++ b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WamBrokerTests.cs @@ -6,7 +6,7 @@ namespace Microsoft.Data.SqlClient.Extensions.Azure.Test; -[Collection("SqlAuthenticationProvider")] +[Collection(SqlAuthenticationProviderCollection.Name)] public class WamBrokerTests { // The SqlClient first-party application client id that is hard-coded in the provider. diff --git a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WindowlessInteractiveConnectionTests.cs b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WindowlessInteractiveConnectionTests.cs index b4bd358d37..3d1cd7d63b 100644 --- a/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WindowlessInteractiveConnectionTests.cs +++ b/src/Microsoft.Data.SqlClient.Extensions/Azure/test/WindowlessInteractiveConnectionTests.cs @@ -7,7 +7,7 @@ namespace Microsoft.Data.SqlClient.Extensions.Azure.Test; /// /// Exercises the windowless WAM diagnostic through real Azure SQL login handshakes. /// -[Collection("SqlAuthenticationProvider")] +[Collection(SqlAuthenticationProviderCollection.Name)] public class WindowlessInteractiveConnectionTests { ///