C# Retrieve Key, Secret, Certificate from Azure KeyVault

ไทย/Eng
This post talk about how to retrieve the information such as “Key”, “Secret”, “Certificate” from Azure KeyVault using C#

Prerequisite

  1. Azure Portal Subscription Account – If you don’t have one. Try it for free
  2. Azure KeyVault with generated certificate – See How To
  3. Visual Studio – This post used VS2017 Preview 2 with .NET Version 4.6.1

Let’s Start
There are 2 tasks to do here:

  • Preparation – Setup the Azure KeyVault and Azure ActiveDirectory.
  • Client Implementation – Get Certificate from Azure KeyVault.

The full project code for this article is available on GitHub

    • Preparation

First, you have to enable the permission for your app to access to your KeyVault.

      1. Go to Azure Portal, then go to “Azure Active Directory” Section. In the “App registrations” section, click on “New application registration”

      1. Specify the “Name” and “Sign-on URL”(It does not have to be the real one but required.). For “Application Type” must be “Web app/ API” in order to generate the client secret for the app.

      1. Once its finish, you’ll see the “Application ID”. This will be your ClientId.

      1. Next, click on “Settings” button as shown in the figure below. Go to “Keys” section. Then specify the description and choose the expires. Finally, click on “Save” button

      1. The secret string will be shown once the saving is complete. This will be the ClientSecret for the App.

You have to copy it immediately because it will be shown only once, it means that you will not able to see it again next time.

You’re finished setting up the Active Directory for your app uses to authenticate to the resource group. For now, your app just gets the credential to the resource group but it can’t be access to your KeyVault yet. So, there is one thing you need to do is to enable this credential in order to retrieve the secret information.

      1. In the “Configure from template” option choose “Key, Secret, & Certificate Management”. Next, “Select Principal” choose the app that was created in the Active Directory.

      1. Now, you are ready to go for your application to retrieve the secret data.
    • Client Implementation
      1. Open Visual Studio and create new project

      1. First, you need to install 2 NuGet packages: “Microsoft.Azure.KeyVault”, “Microsoft.IdentityModel.Clients.ActiveDirectory”


      1. Declare CLIENT_ID and CLIENT SECRET
const string CLIENT_ID = "Key from step 1.3";
const string CLIENT_SECRET = "Key from step 1.5";
      1. Implement the method for ActiveDirectory authentication.
static KeyVaultClient GetClient() => new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(async (string authority, string resource, string scope) =>
{
    var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
    ClientCredential clientCred = new ClientCredential(CLIENT_ID, CLIENT_SECRET);
    var authResult = await context.AcquireTokenAsync(resource, clientCred);
    return authResult.AccessToken;
}));
      1. There are two ways to refer to the certificates in KeyVault
        • Use Certificate Identifier. You can get Certificate Identifier as shown in following figure.

const string CERTIFICATE_IDENTIFIER = "https://key-vault-just-for-test.vault.azure.net/certificates/TestCertificate/ee3c947cdb5241c2a7f711f9770b669e";
        • Use KeyVaule Identifier + Certificate Name


const string KEY_VAULT_IDENTIFIER = "https://key-vault-just-for-test.vault.azure.net/";
const string CERTIFICATE_NAME = "TestCertificate";
      1. Implement you Main method as following.
static void Main(string[] args)
{
    var Client = GetClient();
    var Certificate = Client.GetCertificateAsync(CERTIFICATE_IDENTIFIER).GetAwaiter().GetResult();
    Console.WriteLine(Certificate.X509Thumbprint.ToHexString());

    var Certificate2 = Client.GetCertificateAsync(KEY_VAULT_IDENTIFIER, CERTIFICATE_NAME).GetAwaiter().GetResult();
    Console.WriteLine(Certificate2.X509Thumbprint.ToHexString());
}
      1. This project I’ve written an extension for “string” class for convert the byte array to hex string. The extension class as shown below
public static class StringExtend
{
    public static string ToHexString(this byte[] hex)
    {
        if (hex == null) return null;
        if (hex.Length == 0) return string.Empty;

        var s = new StringBuilder();
        foreach (byte b in hex)
        {
            s.Append(b.ToString("x2"));
        }
        return s.ToString();
    }
}
      1. Now your project is ready to go. The result will be shown as following.

You can also create, update or delete the keys, secrets, and certificates from here.
Thank you for reading. See you in next post.
Happy Coding.

4 thoughts on “C# Retrieve Key, Secret, Certificate from Azure KeyVault

  1. lax Reply

    Great content. I got a small question though. By using this approach, we are getting certificatebundle as a response. Do you know how could I use it a X509Certificate2

    • Shuki Reply

      I Know the PS Way
      But I’m Also will be very glad to know the c# way

Leave a Reply

Your email address will not be published. Required fields are marked *