问题描述
是否可以在Linux VM中使用Azure托管身份来访问Azure SQL DB?我所能找到的只是这份文档 https://docs.microsoft.com/zh-cn/azure/active-directory/managed-identities-azure-resources/tutorial-windows-vm-access-sql 与Windows VM对话.Linux机器上是否有记录的循序渐进的方法?
Is there a way to use Azure managed identities with Linux VMs to access Azure SQL DB? All I could find is this document https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/tutorial-windows-vm-access-sql which specifically speaks to Windows VMs. Is there a documented step-by-step approach for a Linux machine?
推荐答案
使用Linux webapp中的托管身份进行SQL访问.使用Windows VM系统分配的托管身份来访问Azure SQL教程非常适用于Linux,只需关闭代码示例并使用类似以下内容:
SQL access using Managed Identity from Linux webapp is supported. The Use a Windows VM system-assigned managed identity to access Azure SQL tutorial is pretty much applicable to Linux, just dismiss the code sample and use something like this:
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();
完整代码可用此处,只需将连接字符串替换为您的连接字符串即可.
Full code available here, just replace the connection string with yours.
这篇关于使用Azure托管身份访问Azure SQL DB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!