以编程方式在C#中将密钥添加到Key Vault [英] Programatically adding Secrets to Key Vault in C#

查看:193
本文介绍了以编程方式在C#中将密钥添加到Key Vault的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我正在Azure的Key Vault中运行的服务的某些输出放入.我的服务的输出将是用户凭据,这就是为什么我要为此目的使用Key Vault的原因.

I am attempting to put some output from a service I am running in a Key Vault in Azure. The output of my service will be user credentials which is why I want to use Key Vault for this purpose.

到目前为止,我已经尝试了KeyVaultClient的SetSecretAsync方法,但是它对我不起作用,没有收到任何错误消息,但是我也没有看到在目标KeyVault中创建新的机密.我无法找到KeyVaultClient Add Secret方法,因为它不存在,我在这里使用正确的对象/方法吗?

So far, I have tried the KeyVaultClient's SetSecretAsync method, but it's not working for me, I am not getting any error messages however I'm also not seeing a new secret created in my targetted KeyVault. I have not been able to find a KeyVaultClient Add Secret method as it does not exist, am I using the right object/method here?

这里讨论的方法是AddResult.

The method in question here is AddResult.

这是我的代码:

    private static AzureKeyVault instance;
    private static KeyVaultClient client;
    private AzureKeyVault()
    {
        //initialize the azure key vault
        var vaultAddress = ConfigurationManager.AppSettings["VaultUri"];
        client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessToken));


    }
    public static async Task<string> GetAccessToken(string authority, string resource, string scope)
    {
        var clientId = ConfigurationManager.AppSettings["ClientID"];
        var clientSecret = ConfigurationManager.AppSettings["ClientSecret"];
        ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);

        var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
        var result = await context.AcquireTokenAsync(resource, clientCredential);

        return result.AccessToken;
    }


    public static AzureKeyVault GetInstance
    {
        get
        {
            if (instance == null)
            {
                instance = new AzureKeyVault();
            }
            return instance;
        }
    }

    public void AddResult(string machineIPAndPort, BruteForceResult result)
    {
        client.SetSecretAsync("https://vaultURI(redacted).vault.azure.net/", machineIPAndPort, JsonConvert.SerializeObject(result));
    }

推荐答案

使用耐心(等待创建).

Use patience (await creation).

// Let's create a secret and read it back
string vaultBaseUrl = "https://alice.vault.azure.net";
string secret = "from-NET-SDK";

// Await SetSecretAsync
KeyVaultClient keyclient = new KeyVaultClient(GetToken);
var result = keyclient.SetSecretAsync(vaultBaseUrl, secret, "Sup3eS3c5et").Result;

// Print indented JSON response
string prettyResult = JsonConvert.SerializeObject(result, Formatting.Indented);
Console.WriteLine($"SetSecretAsync completed: {prettyResult}\n");

// Read back secret
string secretUrl = $"{vaultBaseUrl}/secrets/{secret}";
var secretWeJustWroteTo = keyclient.GetSecretAsync(secretUrl).Result;
Console.WriteLine($"secret: {secretWeJustWroteTo.Id} = {secretWeJustWroteTo.Value}");

结果:

SetSecretAsync completed:

{  
   "SecretIdentifier":{  
      "BaseIdentifier":"https://alice.vault.azure.net:443/secrets/from-NET-SDK",
      "Identifier":"https://alice.vault.azure.net:443/secrets/from-NET-SDK/59793...",
      "Name":"from-NET-SDK",
      "Vault":"https://alice.vault.azure.net:443",
      "VaultWithoutScheme":"alice.vault.azure.net",
      "Version":"597930b70565447d8ba9ba525a206a9e"
   },
   "value":"Sup3eS3c5et",
   "id":"https://alice.vault.azure.net/secrets/from-NET-SDK/59...",
   "contentType":null,
   "attributes":{  
      "recoveryLevel":"Purgeable",
      "enabled":true,
      "nbf":null,
      "exp":null,
      "created":1508354384,
      "updated":1508354384
   },
   "tags":null,
   "kid":null,
   "managed":null
}

secret: https://alice.vault.azure.net/secrets/from-NET-SDK/59793... = Sup3eS3c5et

您真正应该做的是重写AddResult():

What you should really do is rewrite AddResult():

public bool AddResult(string machineIPAndPort, BruteForceResult result)
{
    await result = client.SetSecretAsync("https://vaultURI(redacted).vault.azure.net/",
        machineIPAndPort, JsonConvert.SerializeObject(result));

    return true;
}

也许将其包装在try-catch中并阅读InnerException,因为

And maybe wrap that in a try-catch and read the InnerException since that's where the meaningful HTTP response body will be. For example, making the request against a Key Vault i don't have access to results in:

而且因为这是云,所以您正与其他任务展开激烈竞争紧急流量,事情将会失败.

And also because this is the cloud, you're in for fierce competition with other mission critical traffic, things will fail.

这篇关于以编程方式在C#中将密钥添加到Key Vault的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆