azuresql连接字符串用户身份验证不是管理员

时间:2020-03-04 08:14:32

标签: azure azure-active-directory azure-sql-database azure-functions connection-string

sql azuredb的boilet板连接字符串使用服务器的admin用户名/ pwd。使用包含的数据库,用户可以登录到特定的数据库而无需访问服务器。

是否可以设置数据库与db用户的连接字符串,而不必使用服务器的admin用户?我正在使用connstring作为azure函数从db获取数据。此外,该用户没有活动目录帐户。

非常感谢您的帮助

2 个答案:

答案 0 :(得分:2)

如果要限制对SQL数据库的访问,还可以将托管身份授予功能应用程序,并在Sql数据库中授予对其的访问权限。这样,只有您的函数将能够连接,并且没有连接字符串被泄漏的风险。

以下是有关如何执行此操作的很好的示例:

https://www.azurecorner.com/using-managed-service-identity-in-azure-functions-to-access-azure-sql-database/

https://docs.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi

答案 1 :(得分:1)

如果要使用非管理员用户在Azure函数中连接Azure SQL,可以使用以下连接字符串

Server=tcp:<sql server name>.database.windows.net,1433;
Initial Catalog=<databse name>;Persist Security Info=False;
User ID=<the non-adimn user name>;
Password=<passsword>;
MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;

例如

  1. 使用SSMS来创建所需数据库的非管理员用户
 CREATE USER jim WITH PASSWORD = '<strong_password>'
 ALTER ROLE db_owner ADD MEMBER jim;
  1. 代码。我使用System.Data.SqlClient 4.6.1在Azure函数中连接Azure sql
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.");
            var constr = "Server=tcp:<sql server name>.database.windows.net,1433;Initial Catalog=<databse name>;Persist Security Info=False;User ID=<the non-adimn user name>;Password=<passsword>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
            using (SqlConnection connection = new SqlConnection(constr))
            {
                var sql = "SELECT * FROM StarWars";
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    connection.Open();
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            log.LogInformation(reader.GetString(2));
                        }
                    }
                }


            }

...

}

enter image description here

enter image description here


更新

如果要使用非管理员用户连接Azure SQL,请更改连接字符串中的User ID值,然后保存在应用程序设置中

  1. 配置连接字符串
Server=tcp:<sql server name>.database.windows.net,1433;
Initial Catalog=<databse name>;Persist Security Info=False;
User ID=<the non-adimn user name>;
Password=<passsword>;
MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
  1. 保存在应用程序设置中 enter image description here

  2. 通过代码获取 enter image description here