简体   繁体   English

在本地开发中使用 azure KeyVault

[英]Using azure KeyVault in local development

I have seen other posts on this, but none of the answers seem to work.我看过其他关于此的帖子,但似乎没有一个答案有效。 I have an azure function app that I am developing locally.我有一个正在本地开发的 azure function 应用程序。 It uses an app setting to get username/password from the key vault.它使用应用程序设置从密钥保管库获取用户名/密码。 When deployed to azure, it works perfectly.当部署到 azure 时,它可以完美运行。 But developing locally, it is not grabbing the data from the vault.但是在本地开发,它并没有从保险库中获取数据。

So in code, I have this:所以在代码中,我有这个:

var password = System.Environment.GetEnvironmentVariable("PASSWORD", EnvironmentVariableTarget.Process);

I have added my user onto the vault access policy, and added the app identity on there also.我已将我的用户添加到保管库访问策略中,并在那里添加了应用程序身份。 Which is why it works in azure.这就是它在 azure 中工作的原因。 I saw this post that mentions setting an environment variable: https://github.com/Azure/azure-functions-host/issues/3907 I tried that, but still no dice.我看到这篇文章提到设置环境变量: https://github.com/Azure/azure-functions-host/issues/3907我试过了,但仍然没有骰子。 Whenever I call the above code, I just get the setting key back, which looks like this:每当我调用上面的代码时,我都会返回设置键,如下所示:

@Microsoft.KeyVault(SecretUri=https://mykeyvault.vault.azure.net/secrets/PASSWORD/e97ba4bf3e2e4919b1899384ea349999)

Of course, it will not work, the keyvault reference is just the feature of function app or web app, it does not apply to the local development.当然不行, keyvault 引用只是 function app 或 web app 的特性,不适用于本地开发。

In local, your option is to get the secret via the SDK manually.在本地,您可以选择手动通过SDK获取密钥。

var client = new SecretClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential());    
secret = client.GetSecret("secret-name");

The code above uses DefaultAzureCredential of Azure.Identity to auth, it will try several credential types to auth in order, one of them is VisualStudioCredential , means it will use the user account logged in the VS to auth, you can also use VisualStudioCredential instead of DefaultAzureCredential directly in the code.上面的代码使用Azure.IdentityDefaultAzureCredential进行身份验证,它会依次尝试几种凭据类型进行身份验证,其中之一是VisualStudioCredential ,表示它将使用登录 VS 的用户帐户进行身份验证,您也可以使用VisualStudioCredential代替DefaultAzureCredential直接在代码中。

Besides, the code will also work when you deploy it to Azure, because DefaultAzureCredential will use ManagedIdentityCredential to auth ie use MSI to get the secret(essentially the keyvault reference feature also uses MSI to get the secret), so you can also use it directly rather than this feature, they all depend on yourself.此外,代码部署到 Azure 时也可以使用,因为DefaultAzureCredential将使用ManagedIdentityCredential进行身份验证,即使用 MSI 获取机密(本质上 keyvault 引用功能也使用 MSI 获取机密),因此您也可以直接使用它而不是这个功能,它们都取决于你自己。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM