如何读取存储在 Azure 密钥保管库中的值/秘密
Posted
技术标签:
【中文标题】如何读取存储在 Azure 密钥保管库中的值/秘密【英文标题】:How to read the values/secrets stored in Azure key vault 【发布时间】:2020-08-28 17:27:14 【问题描述】:我需要使用 clientId、clientSecret、TenantId 和 vaultURL 从 Azure 密钥保管库读取机密/值。我对所有这些都有价值。我需要使用这些值读取存储在 azure key vault 上的值。
对代码有帮助吗?
【问题讨论】:
【参考方案1】:也想分享这些(我看到有人回答了),这样你也能拥有它们
https://docs.microsoft.com/en-us/azure/key-vault/general/developers-guide
和
https://www.microsoft.com/en-us/download/details.aspx?id=45343抢样品
【讨论】:
【参考方案2】:如果您需要示例,可以参考本教程:Azure Key Vault client library for .NET。下面是我的测试代码。
string clientSecret = "client secret";
string clientId = "client id";
var secreturi = "https://****.vault.azure.net";
KeyVaultClient kvClient = new KeyVaultClient(async (authority, resource, scope) =>
var adCredential = new ClientCredential(clientId, clientSecret);
var authenticationContext = new AuthenticationContext(authority, null);
return (await authenticationContext.AcquireTokenAsync(resource, adCredential)).AccessToken;
);
var keyvaultSecret = await kvClient.GetSecretAsync($"secreturi", "testsecret").ConfigureAwait(false);
Console.Write(keyvaultSecret.Value);
【讨论】:
【参考方案3】:您可以尝试以下步骤从 Azure 密钥保管库中读取数据 Link From Microsoft
在 windows Powershell 中运行 1 和 2 命令
1. `az login`
Opens microsoft login page, enter your credentials and you should be logged in.
2. az ad sp create-for-rbac -n <somename> --skip-assignment
this outputs a JSON file
"appId": "XXXXX-XXXXXX-XXXXXX",
"displayName": "somename",
"name": "XXXXX-XXXXXX-XXXXXX",
"password": "XXXXXXXXXXXXXXXXXXXXX",
"tenant": "XXXXX-XXXXXX-XXXXXX"
use the above credentials to call Azure key vault service
// Custom object
var request = new KeyVaultSecretRequest
ClientId = this._config["AzureKeyVault:ClientId"],
ClientSecret = this._config["AzureKeyVault:ClientSecret"], //Password from above JSON
EndPoint = this._config["AzureKeyVault:EndPoint"].ToUri(),
TenantId = this._config["AzureKeyVault:TenantId"],
;
var options = new SecretClientOptions()
Retry =
Delay= TimeSpan.FromSeconds(2),
MaxDelay = TimeSpan.FromSeconds(16),
MaxRetries = 5,
Mode = RetryMode.Exponential,
;
var credentials = new ClientSecretCredential(request.TenantId, request.ClientId, request.ClientSecret);
var client = new SecretClient(request.EndPoint, credentials, options);
KeyVaultSecret secret = await client.GetSecretAsync(request.Key).ConfigureAwait(false);
response.Item = secret.Value;
【讨论】:
以上是关于如何读取存储在 Azure 密钥保管库中的值/秘密的主要内容,如果未能解决你的问题,请参考以下文章
如何保护 Azure Key Vault 中的 blob 存储访问密钥
Azure 磁盘加密 - 通过带有密钥保管库的 Terraform - VmExtensionProvisioningError