【问题标题】:Using Azure Active Directory Interactive when authenticating from Azure Functions to Azure SQL DB从 Azure Functions 向 Azure SQL DB 进行身份验证时使用 Azure Active Directory Interactive
【发布时间】:2020-01-02 15:40:33
【问题描述】:

我正在尝试使用 Azure Active Directory 托管标识和 Active Directory Interactive 对从 Azure 函数到 Azure SQL DB 的访问进行身份验证。在尝试从应用服务向 Azure SQL DB 进行身份验证时,我已成功使用 https://docs.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi 处的说明,但在这种情况下,我可以在 Web.config 文件中以声明方式设置身份验证提供程序。 Azure Functions 似乎没有 Web.config 文件。如何以编程方式执行与在 Azure Functions 的 Web.config 文件中以声明方式执行的相同操作?还是有更简单的方法可以在这里使用?我试图避免嵌入机密或使用键值来存储机密,并且我想要一个解决方案,我仍然可以在 Visual Studio 中本地调试 Azure Functions,就像我可以为应用服务一样。

谢谢, --邦妮

【问题讨论】:

    标签: .net azure-active-directory azure-sql-database azure-sdk azure-managed-identity


    【解决方案1】:

    如何以编程方式执行与声明方式相同的操作 在 Azure Functions 的 Web.config 文件中?或者有没有更简单的 在这里使用的方法?


    根据我的测试,如果我们想在Azure函数中使用Azure MSI连接Azure SQL,请参考以下步骤:

    1. Create function app project in VS2019

    2. 配置 local.setting.json

    {
      "IsEncrypted": false,
      "Values": {
        "AzureWebJobsStorage": "<your storage connection string>",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet"
      },
      "ConnectionStrings": {
        "SQLConnectionString": "Server=tcp:<server name>.database.windows.net,1433;Initial Catalog=<db name>;"
      }
    
    }
    
    1. Configure MSI for VS

      一个。登录 Visual Studio 并使用Tools > Options 打开选项。

      b.选择Azure Service Authentication,输入您的 Azure SQL 管理员帐户并选择确定。

    2. 开发功能 例如

    /* please install sdk :
       Install-Package Microsoft.Azure.Services.AppAuthentication -Version 1.3.1
       Install-Package  System.Data.SqlClient -Version 4.6.1
    
    */
    [FunctionName("Function1")]
            public static async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
                ILogger log)
            {
                log.LogInformation("C# HTTP trigger function processed a request.");
                string str = "SQLConnectionString";
                string conStr = GetSqlAzureConnectionString(str);
                var azureServiceTokenProvider = new AzureServiceTokenProvider();
                string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://database.windows.net/");
    
                var conn = new SqlConnection(conStr);
                conn.AccessToken = accessToken;
                string result = "";
                var sql = "select * from StarWars where episode=1";
                using (SqlCommand command = new SqlCommand(sql, conn))
                {
                    conn.Open();
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
    
                        while (reader.Read()) {
    
                            result = reader.GetString(2);
                        }
                    }
                }
                return new OkObjectResult($"Hello, {result}");
    
            }
    
            private static string GetSqlAzureConnectionString(string SQLConnectionString)
            {
                string conStr = System.Environment.GetEnvironmentVariable($"ConnectionStrings:{SQLConnectionString}", EnvironmentVariableTarget.Process);
                if (string.IsNullOrEmpty(conStr)) // Azure Functions App Service naming convention
                    conStr = System.Environment.GetEnvironmentVariable($"SQLAZURECONNSTR_{SQLConnectionString}", EnvironmentVariableTarget.Process);
                return conStr;
            }
    
    1. 使用 Visual Studio 调试函数。请注意,我们需要在调试之前安装Azure Functions Core Tools

    另外,如果要调试后发布,请参考以下步骤

    1. 创建 Azure 函数
    2. Configure MSI for function app

    3. 配置 Azure SQL

      一个。 Use your Azure Sql AD admin to connect Azure SQL vai SSMS

      b.将 MSI 添加到您需要使用的数据库中

      USE [<db name>]
      GO
      create user [<function app name>] from external provider
      ALTER ROLE db_owner ADD MEMBER [<function app name>]
      
    4. 在 Azure 函数应用程序设置中添加连接字符串

    5. Publish it with Visual Studio

    【讨论】:

    • 感谢您的详细回复。我想出了一个类似的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多