Error in Azure SQL Server Database connection using Azure Function for python with ActiveDirectoryMSI Authentication

被刻印的时光 ゝ 提交于 2020-02-24 12:50:08

问题


I am trying to connect the Azure SQL Database from Azure functions for python using ActiveDirectoryMSI Authentication.

Please check the below code:-

import logging
from . import hy_param
import sys
import pyodbc
import azure.functions as func


def 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
    )

Please check the below Error :-

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)')

Is there any way to connect Azure, SQL Database from Azure functions using ActiveDirectoryMSI?


回答1:


You can try the code below to use MSI access token to connect to your Azure SQL(Before you run this code , pls make sure your function MSI has been enabled and it has permission to access your 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))

Pls edit the connection string with your won server name and db name

This is the test result on my side :



来源:https://stackoverflow.com/questions/57849384/error-in-azure-sql-server-database-connection-using-azure-function-for-python-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!