为了账号安全,请及时绑定邮箱和手机立即绑定

使用带有 ActiveDirectoryMSI 身份验证的 Python 的 Azure 函数连接

使用带有 ActiveDirectoryMSI 身份验证的 Python 的 Azure 函数连接

UYOU 2022-05-24 15:02:42
我正在尝试使用 ActiveDirectoryMSI 身份验证从用于 python 的 Azure 函数连接 Azure SQL 数据库。请检查以下代码:-import loggingfrom . import hy_paramimport sysimport pyodbcimport azure.functions as funcdef main(req: func.HttpRequest) -> func.HttpResponse:    logging.info('Python HTTP trigger function processed a request.')    try:        connection = pyodbc.connect('driver={%s};server=%s;database=%s;Authentication=ActiveDirectoryMSI' % (hy_param.sql_driver, hy_param.server_name, hy_param.database_name))        sql_db = connection.cursor()        logging.info("MSSQL Database Connected")    except Exception as e:        return func.HttpResponse(f"Error in sql database connection : {e}", status_code=400)        sys.exit()    return func.HttpResponse(            "Database Connected",            status_code=200    )请检查以下错误:-Error in sql database connection : ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]SSL Provider: [error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed:self signed certificate] (-1) (SQLDriverConnect)')有什么方法可以使用 ActiveDirectoryMSI 从 Azure 函数连接 Azure、SQL 数据库?
查看完整描述

2 回答

?
千万里不及你

TA贡献1784条经验 获得超9个赞

您可以尝试使用下面的代码使用 MSI 访问令牌连接到您的 Azure SQL(在运行此代码之前,请确保您的功能 MSI 已启用并且它有权访问您的 Azure SQL):


import logging

import os

import azure.functions as func

import pyodbc

import requests 

import struct


msi_endpoint = os.environ["MSI_ENDPOINT"]

msi_secret = os.environ["MSI_SECRET"]


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


   token_auth_uri = f"{msi_endpoint}?resource=https%3A%2F%2Fdatabase.windows.net%2F&api-version=2017-09-01"

   head_msi = {'Secret':msi_secret}

   resp = requests.get(token_auth_uri, headers=head_msi)

   access_token = resp.json()['access_token']


   accessToken = bytes(access_token, 'utf-8');

   exptoken = b"";

   for i in accessToken:

        exptoken += bytes({i});

        exptoken += bytes(1);

   tokenstruct = struct.pack("=i", len(exptoken)) + exptoken;


   conn = pyodbc.connect("Driver={ODBC Driver 17 for SQL Server};Server=tcp:andyserver.database.windows.net,1433;Database=database2", attrs_before = { 1256:bytearray(tokenstruct) });


   cursor = conn.cursor()

   cursor.execute("select @@version")

   row = cursor.fetchall()

   return func.HttpResponse(str(row))

请使用您赢得的服务器名称和数据库名称编辑连接字符串


这是我这边的测试结果:

//img1.sycdn.imooc.com//628c83470001351314260816.jpg

查看完整回答
反对 回复 2022-05-24
?
拉丁的传说

TA贡献1789条经验 获得超8个赞

使用 SDK 和 ODBC 驱动程序直接连接到 Azure SQL 有一种更好的新方法。

你需要:

  1. 启用 Azure 函数托管服务标识 (MSI)

  2. 为 Azure SQL Server 启用 AAD 集成

  3. 将 Azure Function MSI 用户添加到数据库

  4. Authentication=ActiveDirectoryMsi你的pyodbc.connect.

要将 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>通常是 Azure 函数名称。您也可以 Get-AzureADObjectByObjectId -ObjectIds在 PowerShell 中使用它


这是一个 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))

这里有一个完整的项目,您可以作为示例:https ://github.com/crgarcia12/azure-function-msi-python


查看完整回答
反对 回复 2022-05-24
  • 2 回答
  • 0 关注
  • 143 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信