Search code examples
azureodbcazure-sql-databasepyodbcmulti-factor-authentication

Connect to Azure SQL in Python with MFA Active Directory Interactive Authentication without using Microsoft.IdentityModel.Clients.ActiveDirectory dll


To connect to Azure SQL Database using MFA (which is in SSMS as "Active Directory - Universal") Microsoft recommends and currently only has a tutorial on connecting with C# using Microsoft.IdentityModel.Clients.ActiveDirectory

Setting Authentication='Active Directory Interactive'; in a regular ODBC connection string from Python or Powershell results in the error

Cannot find an authentication provider for 'ActiveDirectoryInteractive'

This seems to be because per Microsoft's example code at https://learn.microsoft.com/en-us/azure/sql-database/active-directory-interactive-connect-azure-sql-db you need to explicitly create your own auth provider class when creating the connection:


        public static void Main(string[] args)
        {
            var provider = new ActiveDirectoryAuthProvider();

            SC.SqlAuthenticationProvider.SetProvider(
                SC.SqlAuthenticationMethod.ActiveDirectoryInteractive,
                //SC.SqlAuthenticationMethod.ActiveDirectoryIntegrated,  // Alternatives.
                //SC.SqlAuthenticationMethod.ActiveDirectoryPassword,
                provider);

            Program.Connection();
        }

I want to connect with pyodbc, so I can't implement the ActiveDirectoryInteractive provider.

Is there any way to generically acquire a token using OAuth and use it in the connection string, or otherwise implement the ActiveDirectoryInteractive provider without using .NET?


Solution

  • ODBC driver support the MFA authentication, but windows only: enter image description here

    I tested in Python pyodbc and it also works.

    Here is my pyodbc code which connect to my Azure SQL database with AAD MFA authentication:

    import pyodbc
    server = '***.database.windows.net'
    database = 'Mydatabase'
    username ='****@****.com'
    Authentication='ActiveDirectoryInteractive'
    driver= '{ODBC Driver 17 for SQL Server}'
    conn = pyodbc.connect('DRIVER='+driver+
                          ';SERVER='+server+
                          ';PORT=1433;DATABASE='+database+
                          ';UID='+username+
                          ';AUTHENTICATION='+Authentication
                          )
    
    print(conn)
    

    It works well in my windows environment. enter image description here

    Hope this helps.