In my last post, I talked about using ADAL (now deprecated) with the KeyVaultClient class to get an access token using OAuth2 Client Credentials Grant flow and query Azure Key Vault with that access token. In this post, I’ll talk about using a couple of new classes in the Azure SDK for .NET library to accomplish the same goal. We will use Azure.Identity name space for our Azure AD token acquisition with either a certificate or a secret and the SecretClient class to manage Azure Key Vault secret. Refer to my last post for setting up an Azure Key Vault and Application Registration. Below is the code sample showing how this is done.

using Azure.Core.Diagnostics;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using System;
using System.Diagnostics.Tracing;
using System.Security.Cryptography.X509Certificates;

namespace ConsoleAppKV
{
    class Program
    {
        static void Main(string[] args)
        {
// this is only for diagnostics reason
            AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger(EventLevel.Verbose);
            SecretClientOptions options = new SecretClientOptions()
            {
                Diagnostics =
                    {
                        IsLoggingContentEnabled = true,
                        IsLoggingEnabled = true
                    }
            };

            String keyVaultUrl = "https://<vault name>.vault.azure.net/";
            String certPath = $"C:\\<path_to_pfx_file>\\cert.pfx";
            String tenantID = "<tenant ID>";
            String clientID = "<Application ID>";
            String pfxpassword = "<password for pfx file>";
            String secret = "<Application Secret>";
// using certificate
            X509Certificate2 cer = new X509Certificate2(certPath, pfxpassword, X509KeyStorageFlags.EphemeralKeySet);

            var credential = new ClientCertificateCredential(tenantID, clientID, cer);

// using secret
            var credential2 = new ClientSecretCredential(tenantID, clientID, secret);

// authenticate with a secret
            var client = new SecretClient(new Uri(keyVaultUrl), credential2,options);
// use the below if you want to authenticate with a certificate:
//            var client = new SecretClient(new Uri(keyVaultUrl), credential,options);

// as mentioned above, if you don't want to turn on diagnostics then use the following to create the SecretClient
// var client = new SecretClient(new Uri(keyVaultUrl), credential);
            KeyVaultSecret result = client.GetSecret("<secret name>");
            Console.WriteLine(result.Value);
        }
    }
}

References

Azure Key Vault Developer’s Guide

Azure.Security.KeyVault.Secrets samples for .NET – Code Samples | Microsoft Docs

Azure.Security.KeyVault.Certificates samples for .NET – Code Samples | Microsoft Docs

Azure.Security.KeyVault.Keys samples for .NET – Code Samples | Microsoft Docs

Leave a Comment