Skip to content

Instantly share code, notes, and snippets.

@andrewmatveychuk
Last active June 7, 2024 09:13
Show Gist options
  • Save andrewmatveychuk/45e9c50b0be362cb90a75de0c3262868 to your computer and use it in GitHub Desktop.
Save andrewmatveychuk/45e9c50b0be362cb90a75de0c3262868 to your computer and use it in GitHub Desktop.
Using the DefaultAzureCredential class and environment variables to read a certificate from a local file and retrieve a Key Vault secret
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
var keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME"); // Getting the Key Vault name from an environment variable
if (keyVaultName is not null) // Checking if the environment variable is set
{
Console.WriteLine($"Key Vault name: {keyVaultName}");
var keyVaultUri = "https://" + keyVaultName + ".vault.azure.net";
var client = new SecretClient(new Uri(keyVaultUri), new DefaultAzureCredential()); // Using the DefaultAzureCredential class to authenticate
try
{
KeyVaultSecret secret = await client.GetSecretAsync("myTestSecret1"); // Replace 'myTestSecret1' with your secret name
Console.WriteLine($"Secret value is: {secret.Value}");
}
catch (AuthenticationFailedException e)
{
Console.WriteLine($"[ERROR] Authentication Failed. {e.Message}");
}
}
else
{
Console.WriteLine("[ERROR] The KEY_VAULT_NAME environment variable is not set.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment