![](/img/trans.png)
[英]Token-based authentication support for Azure SQL DB using Azure AD auth
[英]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. 我们目前没有为其保留完整的样本,但本文概述了一些关键要素。
https://database.windows.net/
作为资源字符串。 请注意,您需要保留尾部斜杠,否则发出的令牌将不起作用。这适用于 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.