Azure Key Vault - 获取多个秘密

问题描述 投票:0回答:1

使用 C# 中的 Azure Key Vault 库,我希望从我们的 Vault 中获取机密作为查找工具。 问题是 1 台 PC 最多可以有 4 个不同的条目,例如

PC1-1/1/2024, PC1-2/2/2024, PC1-3/3/2024
等。

查看文档和一些谷歌搜索,我似乎无法找到一种方法来搜索多个秘密而不必获取所有秘密。获取所有秘密是不可行的,因为我们有 30k 个条目,大约需要 20 分钟才能检索到所有秘密。

有人知道如何检索具有相似名称的多个秘密吗?我知道我不能使用星号/通配符

c# azure-keyvault
1个回答
0
投票

有人知道如何检索具有相似名称的多个秘密吗?我知道我不能使用星号/通配符。

您可以使用下面的代码通过 .NET 检索具有相似名称的多个机密。

代码:

using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

public class Program
{
    public static async Task Main(string[] args)
    {
        var vaultUri = "https://venkat678.vault.azure.net/";
        var secretNamePrefix = "pc1";

        var secrets = await GetSecretsAsync(vaultUri, secretNamePrefix);

        foreach (var secret in secrets)
        {
            Console.WriteLine($"{secret.Key}: {secret.Value}");
        }
    }

    public static async Task<Dictionary<string, string>> GetSecretsAsync(string vaultUri, string secretNamePrefix)
    {
        var client = new SecretClient(new Uri(vaultUri), new DefaultAzureCredential());

        var secrets = new Dictionary<string, string>();

        await foreach (var page in client.GetPropertiesOfSecretsAsync().AsPages())
        {
            foreach (var secret in page.Values)
            {
                if (secret.Name.StartsWith(secretNamePrefix))
                {
                    var secretValue = await client.GetSecretAsync(secret.Name);
                    secrets.Add(secret.Name, secretValue.Value.Value);
                }
            }
        }

        return secrets;
    }
}

上面的代码使用 key Vault 的 URI 和秘密名称的前缀来调用

GetSecretsAsync
方法。该方法使用
ListSecretsAsync
类的
SecretClient
方法检索页面中的机密,并根据指定的前缀过滤机密。该方法返回一个字典,将每个秘密名称映射到其输出中的值。

输出:

pc1-1: aNwxxxx8=
pc1-10: d8dvXkAHNxxx1bE=
pc1-100: xxxe56awwKEQbyUWXxcK7KbJn4MUCgWQ=
pc1-11: xU6PSRTOgl8rbSoWxxxAhl+y9PmfQd0=
pc1-12: 8nVVQxxxKxxhKFGAY=
pc1-13: Kd27OZ/9wxxHZ9PKooI=
pc1-14: xxxlGvZPxxxSwT20w/qVC8QL7c

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.