简体   繁体   English

Accessing Azure SQL Server using 1) Python (local script--not going to be Azure function), 2) pyodbc & 3) Azure user-managed identity

[英]Accessing Azure SQL Server using 1) Python (local script--not going to be Azure function), 2) pyodbc & 3) Azure user-managed identity

I've created a Python script on my local machine & I'm attempting to authenticate into an Azure SQL Server (serverless (ie, not managed instance)).我在我的本地机器上创建了一个 Python 脚本 & 我正在尝试验证到 Azure SQL 服务器(无服务器(即非托管)实例) Rather than storing creds in code, I want to utilize user-managed identity (UMI) to authenticate into my SQL Server.我不想将凭据存储在代码中,而是想利用用户管理的身份 (UMI) 对我的 SQL 服务器进行身份验证。

I created the UMI in Azure portal, assigned it to my SQL Server & gave it read, write & admin authorization in SQL server.我在 Azure 门户中创建了 UMI,将其分配给我的 SQL 服务器并在 SQL 服务器中授予它读取、写入和管理权限。

I'm utilizing pyodbc in my script & I believe I'm having trouble with the connection string.我在我的脚本中使用了 pyodbc 并且我相信我在使用连接字符串时遇到了问题。 After reviewing documentation & vids I thought it might be the case I could simply use the UMI client id rather than using Key Vault (as I prefer not to use that if at all possible);在查看文档和视频后,我认为可能是我可以简单地使用 UMI 客户端 ID 而不是使用 Key Vault(因为我宁愿尽可能不使用它); similarly, I don't want to use the ODBC GUI Client (ie, ODBC Data Source Administrator) to store creds if I don't have to.同样,如果我不需要,我不想使用 ODBC GUI 客户端(即 ODBC 数据源管理员)来存储凭据。

My thought is at the very least I have to pass in the UMI client id string via the pyodbc connection string, but then again I really don't have a lot of experience with this.我的想法是至少我必须通过 pyodbc 连接字符串传入 UMI 客户端 ID 字符串,但话又说回来,我真的没有太多这方面的经验。

Here is my connection string:这是我的连接字符串:

db_connect = pyodbc.connect(f"DRIVER={pyodbc_driver}; SERVER={pyodbc_server}; DATABASE={pyodbc_db}; UID={pyodbc_umi_client_id}; Authentication=ActiveDirectoryMsi", autocommit=True)

Here is the error I'm getting:这是我得到的错误:

...Failed to authenticate the user 'pyodbc_umi_client_id' in Active Directory (Authentication option is 'ActiveDirectoryMSI').\r\nError code 0xA190; ...无法在 Active Directory 中对用户“pyodbc_umi_client_id”进行身份验证(身份验证选项为“ActiveDirectoryMSI”)。\r\n错误代码 0xA190; state 41360\r\n (0); state 41360\r\n (0); [CE267] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Timeout error [258]. [CE267] [Microsoft][用于 SQL 服务器的 ODBC 驱动程序 17]TCP 提供程序:超时错误 [258]。 (258); (258); [CE267] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0); [CE267] [Microsoft][ODBC Driver 17 for SQL Server]登录超时(0); [CE267] [Microsoft][ODBC Driver 17 for SQL Server]Unable to complete login process due to delay in login response (258)") [CE267] [Microsoft][ODBC Driver 17 for SQL Server]由于登录响应延迟(258)无法完成登录过程”)

For the UID, I've tried the client ID string from the UMI on the Azure portal.对于 UID,我在 Azure 门户网站上尝试了来自 UMI 的客户端 ID 字符串。 Additionally, I also tried importing the following from one of the Azure modules:此外,我还尝试从 Azure 模块之一导入以下内容:

from azure.identity import DefaultAzureCredential
...
pyodbc_umi_client_id = 'client_id' # client id string from umi in azure portal
db_umi_crd = DefaultAzureCredential(managed_identity_client_id=pyodbc_umi_client_id)

Here is all the script with identifying info removed it somehow it is helpful:这是所有删除了识别信息的脚本,它以某种方式很有帮助:

"""Dec 27, 2021

Want to connect to SQL db by using Azure
user-managed identity (UMI).
"""

import datetime
from azure.identity import DefaultAzureCredential
import pyodbc


# global vars
program_name = 'AZURE SQL UMI CONNECTION' 
original_date = datetime.datetime(2021, 12, 27)


def main():
    """Run main part (i.e., all functions) of the program

    Arguments:
        None

    Returns:
        None

    Raises:
        None

    """
    print_header(program_name, original_date)
    db_work()


def db_work():
    """Connect to the db and do work

        Arguments:
        None

    Returns:
        None

    Raises:
        None
    """
    # connection string vars
    pyodbc_driver = '{ODBC Driver 17 for SQL Server}'
    pyodbc_server = 'tcp:server_url,1433'
    pyodbc_db = 'sql_db'
    pyodbc_umi_client_id = 'client_id' # client id string from umi in azure portal
    db_umi_crd = DefaultAzureCredential(managed_identity_client_id=pyodbc_umi_client_id)

    # connection string
    # db_connect = pyodbc.connect(f"DRIVER={pyodbc_driver}; SERVER={pyodbc_server}; DATABASE={pyodbc_db}; UID={db_umi_crd}")
    db_connect = pyodbc.connect(f"DRIVER={pyodbc_driver}; SERVER={pyodbc_server}; DATABASE={pyodbc_db}; UID={pyodbc_umi_client_id}; Authentication=ActiveDirectoryMsi", autocommit=True)

    # db cursor
    db_cursor = db_connect.cursor()

    # do work
    rows = db_cursor.execute('select * from orderitems').fetchall()
    for row in rows:
        print(row)


def print_header(program_name, original_date, border='*'):
    """Print header indicating name of program

    Arguments:
        Program name: Positional arg. This is global var.
        Original Date: Positional arg. Date script was originally created.
        Border: Keyword arg. Border that is to print around name of program.

    Returns:
        None

    Raises:
        None
    """
    program_name_len = len(program_name) + len(str(original_date))
    print()
    print(border * program_name_len)
    print(program_name, ' ', str(original_date))
    print(border * program_name_len)
    print()



if __name__ == '__main__':
    main()

Thanks for your time.谢谢你的时间。

I want to utilize user-managed identity (UMI) to authenticate into my SQL Server.我想利用用户管理的身份 (UMI) 对我的 SQL 服务器进行身份验证。

As suggested by @Ondrej here正如@Ondrej 在这里所建议的那样

Currently, the server identity for Azure SQL does not support user-assigned managed identities (UMI)目前,Azure SQL 的服务器标识不支持用户分配的托管标识 (UMI)

Based on the MS DOC基于MS DOC

The ODBC Driver on Linux and macOS before version 17.6 only supports Azure Active Directory authentication directly against Azure Active Directory. The ODBC Driver on Linux and macOS before version 17.6 only supports Azure Active Directory authentication directly against Azure Active Directory. If you are using Azure Active Directory username/password authentication from a Linux or macOS client and your Active Directory configuration requires the client to authenticate against an Active Directory Federation Services endpoint, authentication may fail.如果您从 Linux 或 macOS 客户端使用 Azure Active Directory 用户名/密码身份验证,并且您的 Active Directory 配置要求客户端针对 Active Directory 联合服务端点进行身份验证,则身份验证可能会失败。 As of driver version 17.6, this limitation has been removed.从驱动程序版本 17.6 开始,此限制已被删除。

If trying to authenticate using access token:如果尝试使用访问令牌进行身份验证:

The ODBC Driver version 13.1 only supports this authentication on Windows. ODBC 驱动程序版本 13.1 仅支持 Windows 上的此身份验证。

@AjayKumarGhose-MT @AjayKumarGhose-MT

Received the following from Microsoft after using Microsoft Q&A:使用 Microsoft Q&A 后收到来自 Microsoft 的以下信息:

Thanks for using Microsoft Q&A,.感谢您使用微软问答,。 You are getting this error as you cannot use either user assigned identity or >system assigned managed identity to access from SQL server from you local >environment as these identities are meant for accessing Azure AD protected >resources from other Azure services like Azure functions, web apps etc. You are getting this error as you cannot use either user assigned identity or >system assigned managed identity to access from SQL server from you local >environment as these identities are meant for accessing Azure AD protected >resources from other Azure services like Azure functions, web应用程序等

Please refer to managed identities documentation for details.有关详细信息,请参阅托管身份文档。 You need to either provide the username and password in the code or you can >store these as environment variables.您需要在代码中提供用户名和密码,或者您可以 > 将它们存储为环境变量。

暂无
暂无

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

相关问题 如何使用来自 Azure Cloud Function (python) 的用户管理身份向 Azure KeyVault 发出请求? - How to use User-Managed Identity from Azure Cloud Function (python) in making a request to Azure KeyVault? 如何在我的本地笔记本电脑中使用来自 Django 应用程序的托管服务标识连接到 Azure SQL 服务器 - How to connect to Azure SQL Server using Managed Service Identity from Django application in my local laptop 使用托管标识将 Django 与 Azure MS SQL 服务器数据库连接起来 - Connect Django with Azure MS SQL Server DB using managed identity 本地 Azure Python:函数没有名为“pyodbc”的模块 - Local Azure Python: Function No module named 'pyodbc' 使用托管标识 python 连接到 azure sql - Connect to azure sql with managed identity python 使用托管标识在 python 中使用 azure 函数应用程序 - Stuck with azure function app in python using managed identity 使用 pyodbc 的 azure 函数在本地机器上工作正常,但在 azure 云上不能正常工作 - azure function using pyodbc works fine on local machine, but not on azure cloud 无法使用 pyodbc 连接到 Azure SQL Server - Cannot connect to Azure SQL Server using pyodbc 使用 Azure 托管服务标识 (MSI) 连接 Azure SQL Server 数据库 - Azure SQL Server Database connect using Azure Managed Service Identity (MSI) 迁移 Python ADAL 自定义指标 Azure 函数以支持托管标识 - Migrate Python ADAL Custom Metrics Azure Function to support Managed Identity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM