但是此代码不会在本地运行,即在开发时。为此,我们需要安装 Azure CLI (azure-cli-2.0.29.msi) 以在本地环境中使用 MSI。安装此打开 Microsoft azure 命令提示符并运行“az login”命令并打开命令提示符中提到的 url 并复制该 url 中提示中提到的代码。现在,您也可以在本地和应用服务中使用 MSI 使用密钥保管库。
Dictionary<string, string> secretlist = new Dictionary<string, string>();
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
// TO get access token to azureServices
Task<string> accessToken = azureServiceTokenProvider.GetAccessTokenAsync("https://vault.azure.net");
accessToken.Wait();
var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var all = keyVaultClient.GetSecretsAsync("https://keyvaultName.vault.azure.net/");
string seperator = "secrets/";
foreach (Microsoft.Azure.KeyVault.Models.SecretItem someItem in all.Result)
{
var secretName = someItem.Identifier;
var secretValue = keyVaultClient.GetSecretAsync(secretName.ToString());
secretValue.Wait();
secretlist.Add(secretName.ToString().Substring(secretName.ToString().IndexOf(seperator) + seperator.Length), secretValue.Result.Value);
}