All Articles

Reading secret values from Azure Key Vault programmatically

Recently I had the need to check a few secrets stored in a key vault programmatically. Here is the code I used, slightly modified to be more sharable and only containing the important part with Authentication and getting the secret.

using System;
using System.Threading.Tasks;
using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace GetValueFromAzureKeyVault
{
    internal class Program
    {
        private const string ClientId = "00236395-832c-49bf-8354-7a96093584b2";
        private const string ClientSecret = "04c1f2df-a4fa-498c-901c-c2454461efba";
        private const string DnsName = "https://someurl.vault.azure.net"; 
        private const string SecretName = "secretName"; 

        public static async Task Main()
        {
            var kvc = new KeyVaultClient(Authenticate);
            var secret = await kvc.GetSecretAsync($"{DnsName}/secrets/{SecretName}");
            Console.WriteLine($"The secret value is:{Environment.NewLine}{secret?.Value}");
            Console.ReadLine();
        }

        public static async Task<string> Authenticate(string authority, string resource, string scope)
        {
            var authenticationContext = new AuthenticationContext(authority);
            var clientCredential = new ClientCredential(ClientId, ClientSecret);
            var result = await authenticationContext.AcquireTokenAsync(resource, clientCredential);
            if (result == null) throw new Exception("Auth failed");

            return result.AccessToken;
        }
    }
}