Created
March 3, 2017 04:17
-
-
Save jlattimer/0e576af2eabc40d38cd9baa8df4ed308 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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