从带有前缀的Azure密钥库获取所有机密



我想知道是否可以通过前缀获取所有Azure密钥库机密。

假设我有三个秘密。

key: pre-secret1 
value: value1
key: secret2 
value: value2
key: pre-secret3
value: value3

我想获得所有带有前缀pre的秘密,并将它们序列化为JSON。将来,我会有更多带前缀的秘密,所以我不想手动按秘密阅读。因此,当我添加一个带有前缀的新秘密时,我的函数也会返回一个带有新值的JSON。

问题是:是否可以通过前缀从Azure密钥库中获取机密并动态序列化为JSON?

更新:我想在ASP.NET Core 3.1和C#中使用它。更新2:我添加了如何获得一个秘密。

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

您可以使用以下代码来实现这一点。GetSecretsAsync方法为您提供了一个包含vault中所有密钥和机密的字典。

public async Task<IDictionary<string, string>> GetSecretsAsync(string vaultBaseUrl, string prefix = null, string keyVaultKeyDelimeter = "--", string configurationKeyDelimeter = ":")
{
// validation
BaseUrlValidation(vaultBaseUrl);
// variable declartion
IDictionary<string, string> secretCollection = new Dictionary<string, string>();
var updatedPrefix = string.IsNullOrWhiteSpace(prefix) ? prefix : $"{prefix}{keyVaultKeyDelimeter}";
List<SecretItem> secretIdentifierCollection = new List<SecretItem>();
// reading and adding secrets
var secrets = await this.keyVaultClient.GetSecretsAsync(vaultBaseUrl).ConfigureAwait(false);
string nextPageLink = secrets.NextPageLink;
secretIdentifierCollection.AddRange(secrets);
while (!string.IsNullOrWhiteSpace(nextPageLink))
{
// reading and adding secrets
var nextSecrets = await this.keyVaultClient.GetSecretsNextAsync(nextPageLink).ConfigureAwait(false);
secretIdentifierCollection.AddRange(nextSecrets);
nextPageLink = nextSecrets.NextPageLink;
}
if (!secretIdentifierCollection.Any())
{
return secretCollection;
}
// add filtered secrets to dictionary and remove prefix if any
foreach (var secretId in FilterPrefixMatchingSecrets(updatedPrefix, secretIdentifierCollection))
{
await this.FetchSecretDetailsAsync(updatedPrefix, keyVaultKeyDelimeter, configurationKeyDelimeter, secretCollection, secretId);
}
return secretCollection;
}
private async Task FetchSecretDetailsAsync(string prefix, string keyVaultKeyDelimeter, string configurationKeyDelimeter, IDictionary<string, string> secretCollection, string secretId)
{
var secretDetails = await this.keyVaultClient.GetSecretAsync(secretId).ConfigureAwait(false);
var secretName = secretDetails.SecretIdentifier.Name.Substring(string.IsNullOrWhiteSpace(prefix) ? 0 : prefix.Length).Replace(keyVaultKeyDelimeter, configurationKeyDelimeter);
if (!secretCollection.ContainsKey(secretName))
{
secretCollection.Add(secretName, secretDetails.Value);
}
}

最新更新