使用托管服务标识会阻止在调试模式下连接到 KeyVault

Would using Managed Service Identity prevent connecting to KeyVault in debug mode

我正尝试在我的 Azure Functions 应用程序中实施 Azure KeyVault,遵循这篇文章:https://medium.com/statuscode/getting-key-vault-secrets-in-azure-functions-37620fd20a0b

在文章中,函数应用程序设置为使用 Managed Service Identity (MSI),这样我们就不必使用机密来获取令牌来连接到 Azure KeyVault。因为那样会破坏使用 Azure KeyVault 的目的。

据我了解,可以注册 Azure 应用程序以使用 MSI,以便其他 Azure 资源直接识别它,从而通过消除获取令牌等方式简化连接过程

但是,当我调试我的 Azure 函数应用程序时,我无法连接到 Azure KeyVault 来检索必要的机密。

我觉得这可能正在发生,因为函数应用程序在调试期间 运行 在本地而不是在 Azure 上。

这是我无法连接到 KeyVault 的原因吗?

是的,不幸的是,当 运行 在 Azure Functions 服务中时,MSI 只会获得令牌。大约一周前,我确实用一个新的 #if 区域更新了我的示例,如果处于 DEBUG 模式,我可以使用它从局部变量中提取秘密。

https://github.com/jeffhollan/functions-csharp-keyvault-eventhub/blob/master/ScaleTestV1_NoHost/Http.cs

现在有一个更好的解决方案可以解决在调试模式下本地开发期间使用托管服务身份的问题(至少对于 .NET 应用程序和函数)。

您可以使用 Microsoft.Azure.Services.AppAuthentication 包

相关代码示例..(来自以下参考资料)

using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Azure.KeyVault;
// ...
var azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://vault.azure.net");
// OR
var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

How to use managed identities for App Service and Azure Functions

Microsoft.Azure.Services.AppAuthentication Reference

The Microsoft.Azure.Services.AppAuthentication for .NET library simplifies this problem. It uses the developer's credentials to authenticate during local development. When the solution is later deployed to Azure, the library automatically switches to application credentials.

有关 AzureServiceTokenProvider 如何使用 Visual Studio、Azure CLI 或 Azure AD 集成身份验证获取令牌的更多详细信息。Read here

作为 Rohit Saigal 回答的补充,请注意以下内容:

使用 Azure Key Vault 服务在 Visual Studio 内进行本地开发取决于 "Azure Services Authentication Extension" https://marketplace.visualstudio.com/items?itemName=chrismann.MicrosoftVisualStudioAsalExtension#overview 从 15.6 版本开始集成到 Visual Studio 中,不需要单独安装。

检查视觉 Studio/Tools/Options/Azure 服务身份验证以查看您在 Azure 服务中使用哪个帐户进行身份验证,并进行适当的设置。