Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 <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.
<para>
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 <c>Authentication=Active Directory Default</c> with a configured non-interactive credential for windowless hosts.
To use interactive authentication without WAM, supply a custom
<see cref="P:Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProviderOptions.ApplicationClientId"/> and set
<see cref="P:Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProviderOptions.UseWamBroker"/> to <see langword="false"/>.
WAM cannot be disabled for SqlClient's first-party application ID.
</para>
</remarks>
</SetParentActivityOrWindowFunc>
<SetIWin32WindowFunc>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@
Defaults to <see langword="false"/> when you provide a custom <see cref="ApplicationClientId"/>.
Otherwise, WAM broker mode is used automatically on Windows.
</summary>
<remarks>
Setting this property to <see langword="false"/> 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 <see cref="M:Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProvider.SetParentActivityOrWindowFunc(System.Func{System.Object})"/>.
Windowless hosts should use a non-interactive credential with <c>Authentication=Active Directory Default</c>,
or use their own application registration with WAM disabled if interactive sign-in is required.
</remarks>
</UseWamBroker>
</members>
</docs>
Original file line number Diff line number Diff line change
Expand Up @@ -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.
/// </summary>
private static readonly ConcurrentDictionary<PublicClientAppKey, IPublicClientApplication> s_pcaMap = new();
// Internal for test access.
internal static readonly ConcurrentDictionary<PublicClientAppKey, IPublicClientApplication> s_pcaMap = new();
private static readonly ConcurrentDictionary<TokenCredentialKey, TokenCredentialData> s_tokenCredentialMap = new();
private static readonly SemaphoreSlim s_pcaMapModifierSemaphore = new(1, 1);
private static readonly SemaphoreSlim s_tokenCredentialMapModifierSemaphore = new(1, 1);
Expand Down Expand Up @@ -449,6 +450,30 @@ 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) &&
Comment thread
paulmedynski marked this conversation as resolved.
Resolved
_useWamBroker &&
ex.ErrorCode == "window_handle_required")
{
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,
shouldRetry: false,
retryPeriod: 0,
"Active Directory Interactive authentication with Windows Web Account Manager (WAM) requires a valid parent window handle. " +
Comment thread
paulmedynski marked this conversation as resolved.
Resolved
"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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Comment thread
mdaigle marked this conversation as resolved.
Resolved
public class AADAuthenticationTests
{
[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

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

[Collection(SqlAuthenticationProviderCollection.Name)]
public class ActiveDirectoryInteractiveTests
{
private readonly ITestOutputHelper _output;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 <see cref="SqlAuthenticationProvider"/> registry.
/// </summary>
[CollectionDefinition("SqlAuthenticationProvider")]
[CollectionDefinition(Name)]
public class SqlAuthenticationProviderCollection
{
public const string Name = "SqlAuthenticationProvider";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
// 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.Runtime.InteropServices;
using Microsoft.Identity.Client;

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

/// <summary>
/// Verifies missing-window diagnostics without opening UI or contacting Entra ID.
/// </summary>
[Collection(SqlAuthenticationProviderCollection.Name)]
public class WamBrokerErrorTests
{
/// <summary>
/// Both first-party and custom applications using WAM receive actionable guidance on Windows.
/// Other platforms retain the original MSAL diagnostic.
/// </summary>
[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);
}
}

/// <summary>
/// Non-broker flows, other authentication methods, and unrelated MSAL failures are not
/// relabeled as missing WAM windows.
/// </summary>
[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);
}

/// <summary>
/// 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.
/// </summary>
/// <param name="provider">The provider configuration under test.</param>
/// <param name="method">The authentication method under test.</param>
/// <param name="cause">The MSAL failure to propagate through token acquisition.</param>
/// <returns>The translated authentication failure.</returns>
private static async Task<AuthenticationException> 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);

var cache = ActiveDirectoryAuthenticationProvider.s_pcaMap;
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<AuthenticationException>(() => provider.AcquireTokenAsync(parameters));
}
finally
{
cache.TryRemove(key, out _);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// 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;

/// <summary>
/// Exercises the windowless WAM diagnostic through real Azure SQL login handshakes.
/// </summary>
[Collection(SqlAuthenticationProviderCollection.Name)]
public class WindowlessInteractiveConnectionTests
{
/// <summary>
/// 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.
/// </summary>
[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);
Comment thread
Copilot marked this conversation as resolved.
Resolved
SqlAuthenticationProvider? original =
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);
using var connection = new SqlConnection(builder.ConnectionString);

SqlException exception = async
? await Assert.ThrowsAsync<SqlException>(() => connection.OpenAsync())
: Assert.Throws<SqlException>(() => 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!);
ActiveDirectoryAuthenticationProvider.ClearUserTokenCache();
}
}
}
Loading