繁体   English   中英

pyodbc 是否支持使用 AD 访问令牌而不是用户/密码连接到 Azure SQL DB?

[英]pyodbc will support connecting to an Azure SQL DB using the AD access token instead of user/password?

目前,我使用设备代码凭证来访问 Azure AD。

device_code_credential = DeviceCodeCredential(
        azure_client_id,
        tenant_id=azure_tenant_id,
        authority=azure_authority_uri)

但我仍然需要使用 Azure 帐户用户名/密码连接到 Azure SQL 服务器

driver = 'ODBC Driver 17 for SQL Server'
db_connection_string = f'DRIVER={driver};SERVER={server};' \
    f'DATABASE={database};UID={user_name};PWD={password};'\
    f'Authentication=ActiveDirectoryPassword;'\
    'Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;'
connector = pyodbc.connect(db_connection_string)

在 linux/MacOS 下的 python 中是否有任何方法可以让我使用 device_code_credential 和 access_token 连接到 Azure SQL 服务器?

https://github.com/mkleehammer/pyodbc/issues/228

我只有这个链接,它似乎不起作用。

有人有完整的工作样本吗?

您可以参考本教程: AzureAD/azure-activedirectory-library-for-python: Connect to Azure SQL 数据库

It is doable to connect to Azure SQL Database by obtaining a token from Azure Active Directory (AAD), via ADAL Python. 我们目前没有为其保留完整的样本,但本文概述了一些关键要素。

  1. 您按照使用访问令牌进行连接的说明来配置您的应用程序。 这里还有另一篇类似的博客文章
  2. 您的 SQL 管理员需要将应用注册权限添加到您尝试访问的特定数据库。 请参阅此博客文章中基于令牌的身份验证支持 Azure SQL DB 的详细信息,使用 Azure AD auth by Mirek H Szt
  3. 上面两个文档中都没有特别强调,但是您需要使用https://database.windows.net/作为资源字符串。 请注意,您需要保留尾部斜杠,否则发出的令牌将不起作用。
  4. 将上述配置输入 ADAL Python 的客户端凭据示例
  5. 获得访问令牌后, 在 pyodbc 中以这种方式使用它来连接到 SQL 数据库。

这适用于 AAD 访问令牌。 在 Python 2.x 中,如上面链接的页面所述,扩展令牌并添加长度的示例代码:

token = "eyJ0eXAiOi...";
exptoken = "";
for i in token:
    exptoken += i;
    exptoken += chr(0);
tokenstruct = struct.pack("=i", len(exptoken)) + exptoken;
conn = pyodbc.connect(connstr, attrs_before = { 1256:bytearray(tokenstruct) });

由于烦人的字符/字节拆分,3.x 只涉及稍微多一点:

token = b"eyJ0eXAiOi...";
exptoken = b"";
for i in token:
    exptoken += bytes({i});
    exptoken += bytes(1);
tokenstruct = struct.pack("=i", len(exptoken)) + exptoken;
conn = pyodbc.connect(connstr, attrs_before = { 1256:tokenstruct });

(SQL_COPT_SS_ACCESS_TOKEN 是 1256;它特定于 msodbcsql 驱动程序,因此 pyodbc 没有定义它,并且可能不会。)

希望这可以帮助。

您可以通过

from azure.identity import DeviceCodeCredential

# Recommended to allocate a new ClientID in your tenant.
AZURE_CLI_CLIENT_ID = "04b07795-8ddb-461a-bbee-02f9e1bf7b46"
credential = DeviceCodeCredential(client_id=AZURE_CLI_CLIENT_ID)
databaseToken = credential.get_token('https://database.windows.net/.default')

然后使用 databaseToken.token 作为 Leon Yue 的回答中描述的 AAD 访问令牌。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM