问题
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://docs.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?
回答1:
ODBC driver support the MFA authentication, but windows only:
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.
Hope this helps.
来源:https://stackoverflow.com/questions/58440480/connect-to-azure-sql-in-python-with-mfa-active-directory-interactive-authenticat