简体   繁体   English

使用 Azure 托管服务标识 (MSI) 连接 Azure SQL Server 数据库

[英]Azure SQL Server Database connect using Azure Managed Service Identity (MSI)

I want to Access the Azure SQL Database using python Azure Functions with MSI (Managed Service Identity) authentication.我想使用带有MSI(托管服务标识)身份验证的python Azure Functions访问Azure SQL 数据库

I am trying to find out the how to connect Azure sql with MSI from azure functions for python but i didn't get any information.我试图找出如何将 Azure sql 与 MSI 从用于 python 的 azure 函数连接起来,但我没有得到任何信息。

Is there any way to access the Azure SQL Server database using MSI in Azure Functions?有没有办法在 Azure Functions 中使用 MSI 访问 Azure SQL Server 数据库?

I want to Access the Azure SQL Database without the passing the credentials in my code using azure function for python.我想访问 Azure SQL 数据库,而无需使用 python 的 azure 函数在我的代码中传递凭据。

I enabled the identity option from azure functions for python.我从 azure 函数为 python 启用了身份选项。

If you just want to hide your Azure SQL connection string in your Azure function , using Azure Key Vault and MSI will be the best practices here : just saving your Azure SQL connection string as a secret in Azure key vault and follow this guide to do some configs on your Azure function will meet your requirement: your creds will never appears in your Azure function.如果你只是想在你的 Azure 函数中隐藏你的 Azure SQL 连接字符串,使用 Azure Key Vault 和 MSI 将是这里的最佳实践:只需将你的 Azure SQL 连接字符串保存为 Azure Key Vault 中的秘密,然后按照本指南做一些您的 Azure 函数上的配置将满足您的要求:您的凭据永远不会出现在您的 Azure 函数中。

I created a key vault and stored my SQL sever connection string in Azure key vault as a secret,note the secret identifier as we will use it later :我创建了一个密钥保管库并将我的 SQL 服务器连接字符串作为机密存储在 Azure 密钥保管库中,请注意机密标识符,因为我们稍后将使用它: 在此处输入图片说明

Go to your key vault,config a access policy for your function msi to make sure that your function can access the secret :转到您的密钥保管库,为您的函数 msi 配置访问策略以确保您的函数可以访问机密: 在此处输入图片说明 在此处输入图片说明 save it after your config :在您的配置后保存它: 在此处输入图片说明

This is my python demo code , it is easy as you can see , I am reading "SQLConn" from Azure web app :这是我的 python 演示代码,正如你所看到的,我正在从 Azure Web 应用程序读取“SQLConn”:

import logging
import os
import azure.functions as func
import pyodbc

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    cnxn = pyodbc.connect(os.environ["SQLConn"])
    cursor = cnxn.cursor()
    cursor.execute("select @@version")
    row = cursor.fetchall()
    return func.HttpResponse(str(row))

Let's set its value in app settings :让我们在应用程序设置中设置它的值: 在此处输入图片说明

The value should be :该值应为:

@Microsoft.KeyVault(SecretUri=<secret_uri_with_version which you noted from key valut>)

With the steps done , your azure function will be able to get SQL connection string from key vault and it will not appreared in your function app settings and there is no code need to change .完成这些步骤后,您的 azure 函数将能够从密钥保管库中获取 SQL 连接字符串,并且它不会出现在您的函数应用设置中,并且无需更改代码。

Btw, if you still want to use MSI to get access token to connect to your Azure SQL , I have a new demo posted here , which will be helpful for you.顺便说一句,如果您仍然想使用 MSI 来获取访问令牌以连接到您的 Azure SQL , 我在这里发布了一个新的演示,这将对您有所帮助。

I just did a quick test.我刚刚做了一个快速测试。 Full step by step in here: https://github.com/crgarcia12/azure-function-msi-python完整的一步一步在这里: https : //github.com/crgarcia12/azure-function-msi-python

Summary:概括:

You need to:你需要:

  1. Enable Azure Function Managed Service Identity (MSI)启用 Azure 功能托管服务标识 (MSI)
  2. Enable AAD integration for Azure SQL Server为 Azure SQL Server 启用 AAD 集成
  3. Add The Azure Function MSI User to the DB将 Azure Function MSI 用户添加到数据库
  4. Use Authentication=ActiveDirectoryMsi in your pyodbc.connect .在您的pyodbc.connect使用Authentication=ActiveDirectoryMsi

To add the MSI user to the DB you must connect using the AAD admin and then run this query:要将 MSI 用户添加到数据库,您必须使用 AAD 管理员进行连接,然后运行以下查询:

CREATE USER "<MSI user display name>" FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER "<MSI user display name>" -- grant permission to read to database
ALTER ROLE db_datawriter ADD MEMBER "<MSI user display name>" -- grant permission to write to database

<MSI user display name> is usually the Azure Function Name. <MSI user display name>通常是 Azure 函数名称。 You can also get it using Get-AzureADObjectByObjectId -ObjectIds in PowerShell您还可以在 PowerShell 中使用Get-AzureADObjectByObjectId -ObjectIds获取它

This is the source code of a hello-world function:这是一个 hello-world 函数的源代码:

import logging
import azure.functions as func

# Sql driver
import pyodbc

def main(req: func.HttpRequest) -> func.HttpResponse:

    try:

        logging.info('Python HTTP trigger function processed a request.')

        # Connecting to Azure SQl the standard way
        server = 'tcp:<servername>.database.windows.net' 
        database = '<dbname>' 
        driver = '{ODBC Driver 17 for SQL Server}' # Driver 13 did not work for me

        with pyodbc.connect(
            "Driver="
            + driver
            + ";Server="
            + server
            + ";PORT=1433;Database="
            + database
            + ";Authentication=ActiveDirectoryMsi", # This is important :)
        ) as conn:

            logging.info("Successful connection to database")

            with conn.cursor() as cursor:
                #Sample select query
                cursor.execute("SELECT Name FROM People;") 

                peopleNames = ''
                row = cursor.fetchone() 
                while row: 
                    peopleNames += str(row[0]).strip() + " " 
                    row = cursor.fetchone()

                return func.HttpResponse(f"Hello {peopleNames}!")
    except Exception as e:
        return func.HttpResponse(str(e))

暂无
暂无

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

相关问题 使用托管标识将 Django 与 Azure MS SQL 服务器数据库连接起来 - Connect Django with Azure MS SQL Server DB using managed identity 如何在我的本地笔记本电脑中使用来自 Django 应用程序的托管服务标识连接到 Azure SQL 服务器 - How to connect to Azure SQL Server using Managed Service Identity from Django application in my local laptop Trying to connect Azure SQL database from Azure ML Service using MSI authentication (Without username and passowrd connect the Azure database) - Trying to connect Azure SQL database from Azure ML Service using MSI authentication (Without username and passowrd connect the Azure database) 使用托管标识向 SQL 数据库验证 Azure 应用服务 - Use Managed Identity to authenticate Azure App Service to SQL Database 使用托管标识 python 连接到 azure sql - Connect to azure sql with managed identity python 使用服务主体连接 Azure SQL 服务器 - Connect Azure SQL Server using Service Principal 使用 MSI 的 Azure SQL Server 连接 - Django - Azure SQL Server connection using MSI - Django Accessing Azure SQL Server using 1) Python (local script--not going to be Azure function), 2) pyodbc &amp; 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 使用带有 python 的托管标识创建 Azure 数据工厂链接服务 - creating Azure Data factory linked service using Managed identity with python 使用 Python 中的服务主体 ID 连接 Azure SQL 服务器 - Connect Azure SQL Server using Service Principal ID in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM