Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlattimer/0e576af2eabc40d38cd9baa8df4ed308 to your computer and use it in GitHub Desktop.
Save jlattimer/0e576af2eabc40d38cd9baa8df4ed308 to your computer and use it in GitHub Desktop.
string vaultName = "https://myvaulttest.vault.azure.net";
string secretName = "MyPassword";
//Retrieve the latest version of a secret by name
var getKeyByNameTask = Task.Run(async () => await GetSecretByName(token, vaultName, secretName));
Task.WaitAll(getKeyByNameTask);
if (getKeyByNameTask.Result == null)
throw new InvalidPluginExecutionException("Error retrieving secret versions from key vault");
var retrievedSecretUrl = getKeyByNameTask.Result;
// Retrieve a secret by its url
var getKeyByUrlTask2 = Task.Run(async () => await GetSecretByUrl(token, retrievedSecretUrl));
Task.WaitAll(getKeyByUrlTask2);
if (getKeyByUrlTask2.Result == null)
throw new InvalidPluginExecutionException("Error retrieving secret value from key vault");
//Deserialize the vault response to get the secret
GetSecretResponse getSecretResponse2 = DeserializeResponse<GetSecretResponse>(getKeyByUrlTask2.Result);
//returnedValue is the Azure Key Vault Secret
string returnedValue2 = getSecretResponse2.value;
//Get the most recent, enabled Secret value by name - api-version is required
private async Task<string> GetSecretByName(string token, string vaultName, string secretName)
{
string nextLink = vaultName + "/secrets/" + secretName + "/versions?api-version=2016-10-01";
List<Value> values = new List<Value>();
using (HttpClient httpClient = new HttpClient())
{
while (!string.IsNullOrEmpty(nextLink))
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,
new Uri(nextLink));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = await httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
return null;
var versions = DeserializeResponse<GetSecretVersionsResponse>(response.Content.ReadAsStringAsync().Result);
values.AddRange(versions.value);
nextLink = versions.nextLink;
}
}
Value mostRecentValue =
values.Where(a => a.attributes.enabled)
.OrderByDescending(a => UnixTimeToUtc(a.attributes.created))
.FirstOrDefault();
return mostRecentValue?.id;
}
private DateTime UnixTimeToUtc(double unixTime)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var timeSpan = TimeSpan.FromSeconds(unixTime);
return epoch.Add(timeSpan).ToUniversalTime();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment