You can use below code to achieve this. The GetSecretsAsync
method gives you a dictionary of all the keys and secrets from the 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);
}
}
await client.GetSecretsAsync(VaultUrl)
, filter it then serialize it. Seems to me you're abusing Key Vault for use cases it has never been designed to accommodate. – evilSnobu