Skip to content

WAM broker integration breaks windowless uses #4854

Closed

Description

@zdenek-jelinek

Based on this question on Stack Overflow: https://stackoverflow.com/questions/80009713

When used with Authentication=Active Directory Interactive from Azure Functions local emulator on Windows OS, WAM broker integration in SqlClient fails because it uses an invalid window handle.

The Azure Functions emulator host seems to spawn processes without a console window (i.e. kernel32.dll GetConsoleWindow() returns NULL) and so I think this branch in ActiveDirectoryAuthenticationProvider is taken which causes WAM to fail.

I'd expect the SqlClient to either:

Currently, the exception looks like this:

Microsoft.Data.SqlClient.SqlException (0x80131904): Failed to authenticate the user  in Active Directory (Authentication=ActiveDirectoryInteractive).
Error code 0xwindow_handle_required
A window handle must be configured. See https://aka.ms/msal-net-wam#parent-window-handles
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.GetFedAuthToken(SqlFedAuthInfo fedAuthInfo)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo)
   at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at Microsoft.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, TimeoutTimer timeout, Boolean withFailover)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, IDbConnectionPool pool, Func`3 accessTokenCallback)
   at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionPoolGroupProviderInfo poolGroupProviderInfo, IDbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(IDbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at Microsoft.Data.SqlClient.ConnectionPool.WaitHandleDbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.SqlClient.ConnectionPool.WaitHandleDbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.SqlClient.ConnectionPool.WaitHandleDbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.SqlClient.ConnectionPool.WaitHandleDbConnectionPool.WaitForPendingOpen()
--- End of stack trace from previous location ---
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.<>c__DisplayClass30_0`2.<<ExecuteAsync>b__0>d.MoveNext()
--- End of stack trace from previous location ---
   at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementationAsync[TState,TResult](Func`4 operation, Func`4 verifySucceeded, TState state, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteImplementationAsync[TState,TResult](Func`4 operation, Func`4 verifySucceeded, TState state, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.ExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at AzureFunctionWithEfCore.HttpTriggerCSharp.Run(HttpRequest unused) in C:\Projects\AzureFunctionWithEfCore\HttpTriggerCSharp.cs:line 15
ClientConnectionId:8fad0be6-d01f-4a9c-8dc0-074d339981e9

Activity

  1. github-actions commented on Oct 16, 2026

    @github-actions

    🔍 Triage Summary

    Check Result
    Issue type Bug
    Environment ⚠️ Missing: SqlClient version, .NET target framework, SQL Server version, repro steps (code/connection string), explicit expected vs actual (OS = Windows, Azure Functions local emulator mentioned)
    Area Area\Azure Connectivity
    Duplicates Potentially related (closed): #4414
    Regression Inconclusive (WAM integration was a patch-level addition; the version boundary is not stated)

    Analysis

    With Authentication=Active Directory Interactive, the WAM broker path in ActiveDirectoryAuthenticationProvider.Windows.cs appears to use the console window handle, which is NULL in windowless hosts such as the Azure Functions local emulator. MSAL then fails with an invalid parent window handle error. Severity is probably P2: it affects a specific hosting scenario, but it is a regression-prone behavior and the error message is not actionable.

    Next Steps

    • @zdenek-jelinek, please provide: SqlClient version (and the Azure extensions package version), .NET target framework, SQL Server version, a minimal repro or connection string (redacted), and the full exception text.
    • Once the details are supplied, assign this issue to Copilot coding agent to investigate ActiveDirectoryAuthenticationProvider.Windows.cs. It should skip the WAM broker, or fall back to the non-broker interactive flow, when no valid window handle is available. Failing that, it should throw an exception explaining how to resolve it in a SqlClient context.
    • Review 7.0.2 regression: Active Directory Interactive authentication opens non-browser window after 60+ second delay (worked in 7.0.1) #4414 for related interactive-auth behavior changes.

    Note: This triage summary is auto-generated by an AI agent. The analysis and suggestions above have not been verified by a human maintainer. Please treat as preliminary guidance only.

    Generated by SqlClient Issue Auto-Triage for #4854 · copilot · auto · 23.4 AIC · ⌖ 11.5 AIC · ⊞ 13.6K · ◷

  2. ErikEJ commented on Oct 16, 2026

    @ErikEJ
    Contributor

    @zdenek-jelinek Is there a workaround ??

  3. zdenek-jelinek commented on Oct 16, 2026

    @zdenek-jelinek
    Author

    The 6.1.6 release notes include a snippet that can be adapted to disable WAM:

    var options = new ActiveDirectoryAuthenticationProviderOptions { UseWamBroker = false };
    
    var provider = new ActiveDirectoryAuthenticationProvider(options);
    
    SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, provider);

    EDIT:

    The above is not sufficient. WAM stays enabled even with the above configuration unless ApplicationClientId is provided. Unfortunately, I have no idea what that should be when running Azure Functions locally.

    Would be nice to throw an exception here instead of ignoring the provided configuration.

  4. zdenek-jelinek commented on Oct 16, 2026

    @zdenek-jelinek
    Author

    To make this work without WAM, it's necessary to:

    1. Add the following code to your startup:
      var options = new ActiveDirectoryAuthenticationProviderOptions
      {
          UseWamBroker = false,
          ApplicationClientId = "<your app client ID>"
      };
      
      var provider = new ActiveDirectoryAuthenticationProvider(options);
      
      SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, provider);
    2. Get an app client ID, which means
      1. Create an app registration: Open Azure Portal, navigate to Entra ID choose 'Manage > App Registrations' and click 'New registration' in the top pane
        1. Choose whatever account type you need to use, if you're not sure, use Single tenant-only
        2. In Redirect URI, choose 'Public client/native (mobile & desktop)' and add http://localhost as the value.
        3. Create the App registration
      2. You'll get redirected to the App Registration's Overview page. Grab Application (client) ID from there and add it to the options in the code snippet above.
      3. Configure permissions to access Azure SQL DB
        1. Navigate to 'Manage > API Permissions'
        2. Click 'Add a permission'
        3. Select 'APIs My Organization Uses' (Azure SQL Database is not on the first page for me)
        4. Select Azure SQL Database
        5. Choose 'Delegated Permissions'
        6. Select 'user_impersonation' under available permissions
        7. Confirm

    Database access from the Function should now open a browser window and ask for authentication.

  5. ErikEJ commented on Oct 16, 2026

    @ErikEJ
    Contributor

    @zdenek-jelinek Thanks, that is ridiculous!

  6. mdaigle commented on Oct 16, 2026

    @mdaigle
    Contributor

    Hey @zdenek-jelinek, sorry you're facing this issue.

    To provide some background, the default Entra Id application id used in the driver is a Microsoft first-party Entra Id app. First party apps are owned and maintained by Microsoft and are subject to increased scrutiny and security requirements. In this case, it was a requirement for the First party app that connections go through WAM on platforms on which it's available. We provide the first party app primarily to make local development easier, so that you don't have to go through the application registrations steps described above every time you want to test something out. When developing a production application or service, we recommend that you do create your own Entra Id application so that you have full control over its settings.

    Unfortunately, as you've identified, WAM does require a valid parent window handle to display the interactive auth pop up. For that reason, you should use non-interactive authentication modes (such as Active Directory Default) in headless environments.

    I agree that we should wrap the exception and include a message to use non-interactive auth when a window handle can't be found.

  7. moved this from To triage to Backlog in SqlClient Boardon Oct 16, 2026
  8. zdenek-jelinek commented on Oct 17, 2026

    @zdenek-jelinek
    Author

    Thanks for your reply.

    you should use non-interactive authentication modes (such as Active Directory Default) in headless environments

    This makes total sense to me.

    The issue is that the headless environment looks like this:
    Image

    Anyway, SqlClient telling the user they should not use interactive login would definitely be an improvement here.

  9. zdenek-jelinek commented on Oct 17, 2026

    @zdenek-jelinek
    Author

    First party apps are owned and maintained by Microsoft and are subject to increased scrutiny and security requirements. In this case, it was a requirement for the First party app that connections go through WAM on platforms on which it's available.

    I guess this is not my problem but I don't think you'll be able to enforce this anyway.

    It's currently possible to revert to the legacy browser approach on Windows by overwriting ActiveDirectoryAuthenticationProvider._useWamBroker with reflection/unsafe accessor:

    var provider = new ActiveDirectoryAuthenticationProvider();
    
    GetUseWamBrokerFieldReference(provider) = false;
    
    SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, provider);
    
    [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_useWamBroker")]
    static extern ref bool GetUseWamBrokerFieldReference(ActiveDirectoryAuthenticationProvider provider);
  10. moved this from Backlog to In progress in SqlClient Boardon Oct 19, 2026
  11. moved this from In progress to Done in SqlClient Boardon Oct 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions