Programatically adding Secrets to Key Vault in C#

[亡魂溺海] 提交于 2019-12-03 14:05:33

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}");

Result:

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

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;
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!