使用 Azure 托管标识访问 Azure SQL 数据库

Using Azure managed Identities to access Azure SQL DB

是否可以通过 Linux VM 使用 Azure 托管身份来访问 Azure SQL 数据库?我所能找到的就是这篇文档 https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/tutorial-windows-vm-access-sql,它专门针对 Windows 虚拟机。 Linux 机器是否有记录的分步方法?

托管身份似乎不支持 Linux VM 访问 Azure SQL 数据库。

有一个类似的问题here. And there is a workaround which uses the cross-platform .NET core libraries, you could refer to it

SQL 支持使用来自 Linux webapp 的托管身份进行访问。 Use a Windows VM system-assigned managed identity to access Azure SQL tutorial 几乎适用于 Linux,只需忽略代码示例并使用如下内容:

var azureServiceTokenProvider = new AzureServiceTokenProvider();
var accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://database.windows.net/");

using
var sqlConnection = new SqlConnection(configuration.GetConnectionString("Default")) {
 AccessToken = accessToken
};
using
var sqlCommand = new SqlCommand("SELECT @@VERSION", sqlConnection);
await sqlConnection.OpenAsync();
var version = (string) await sqlCommand.ExecuteScalarAsync();

完整代码可用 here,只需将连接字符串替换为您的即可。