使用 MFA Active Directory 交互式身份验证在 Python 中连接到 Azure SQL,而不使用 Microsoft.IdentityModel.Clients.ActiveDirectory dll

dmi*_*mi_ 6 odbc azure pyodbc azure-sql-database multi-factor-authentication

要使用 MFA(在 SSMS 中作为“Active Directory - Universal”)连接到 Azure SQL 数据库,Microsoft 建议并且目前只有使用 Microsoft.IdentityModel.Clients.ActiveDirectory 与 C# 连接的教程

Authentication='Active Directory Interactive';从 Python 或 Powershell设置常规 ODBC 连接字符串会导致错误

Cannot find an authentication provider for 'ActiveDirectoryInteractive'
Run Code Online (Sandbox Code Playgroud)

这似乎是因为根据https://docs.microsoft.com/en-us/azure/sql-database/active-directory-interactive-connect-azure-sql-db 上的Microsoft 示例代码,您需要明确创建自己的创建连接时的身份验证提供程序类:


        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();
        }
Run Code Online (Sandbox Code Playgroud)

我想与pyodbc 连接,所以我无法实现ActiveDirectoryInteractive 提供程序。

有什么方法可以使用 OAuth 获取令牌并在连接字符串中使用它,或者在不使用 .NET 的情况下以其他方式实现 ActiveDirectoryInteractive 提供程序?

Leo*_*Yue 8

ODBC 驱动程序支持 MFA 身份验证,但仅限 Windows: 在此处输入图片说明

我在 Python pyodbc 中进行了测试,它也可以工作。

这是我pyodbc使用 AAD MFA 身份验证连接到 Azure SQL 数据库的代码:

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)
Run Code Online (Sandbox Code Playgroud)

它在我的 windows 环境中运行良好。 在此处输入图片说明

希望这可以帮助。

  • 根据您的设置,您可能不需要在连接字符串中提供密码。如果这样做,我会收到以下错误:“如果身份验证选项为“ActiveDirectoryInteractive”,则不得指定[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]密码选项。您只需将密码插入 Windows 弹出窗口即可。 (3认同)

Eve*_*ela 5

从 MacOS/Linux 使用 AAD MFA 进行身份验证

我遇到了同样的问题,但在 MacOs 上。如上所述,使用“ ActiveDirectoryInteractive ”的 ODBC 选项仅适用于 Windows。

为了使用 AAD MFA 连接到数据库,我还使用了pyodbc,但带有访问令牌。要获得令牌,您需要做一些事情:

要求

  1. Azure CLI

  2. 适用于 SQL Server 的 Microsoft ODBC 驱动程序 (Linux-MAC)

指示

在运行下面的代码之前,您必须使用 azure cli 进行身份验证,从 cmd 运行:az login

from azure.identity import AzureCliCredential
import struct
import pyodbc 

# input params
server = '<your server address>'
database = '<database name>'
query = 'SELECT * from dbo.Address;'

# Use the cli credential to get a token after the user has signed in via the Azure CLI 'az login' command.
credential = AzureCliCredential()
databaseToken = credential.get_token('https://database.windows.net/')

# get bytes from token obtained
tokenb = bytes(databaseToken[0], "UTF-8")
exptoken = b'';
for i in tokenb:
 exptoken += bytes({i});
 exptoken += bytes(1);
tokenstruct = struct.pack("=i", len(exptoken)) + exptoken;

# build connection string using acquired token
connString = "Driver={ODBC Driver 17 for SQL Server};SERVER="+server+";DATABASE="+database+""
SQL_COPT_SS_ACCESS_TOKEN = 1256 
conn = pyodbc.connect(connString, attrs_before = {SQL_COPT_SS_ACCESS_TOKEN:tokenstruct});

# sample query
cursor = conn.cursor()
cursor.execute(query)
row = cursor.fetchone()
while row:
    print (str(row[0]) + " " + str(row[1]))
    row = cursor.fetchone()
Run Code Online (Sandbox Code Playgroud)

参考

https://pypi.org/project/azure-identity/

https://github.com/AzureAD/azure-activedirectory-library-for-python/wiki/Connect-to-Azure-SQL-Database

  • 这是我在整个 Stackoverflow 上找到的唯一真正有效的方法。谢谢。 (5认同)