Create Web API Project to Access Certificate & Key Vault Secret

Create a new Web API project.image

Add package: Microsoft.Azure.KeyVault

Create a new Controller.  Add the following code.

public class KeyVaultController : Controller
{
     public IActionResult Index()
     {
         string result = string.Empty;

        try
         {
             result = new KeyVaultSecretProvider().GetKeyVaultSecret(“MySecret”);
         }
         catch (Exception ex)
         {
             result = ex.ToString();
         }

        return Content(result);
     }
}

Create a new class.  Add the following code.

using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace KeyVault_Cert_WebAPI.Controllers
{
     public class KeyVaultSecretProvider
     {
         public const string ClientID = “YOUR-CLIENT-ID”;
         public static string Thumbprint = “YOUR-THUMBPRINT”;
         public const string VaultURL = “https://YOUR-KEY-VAULT.vault.azure.net/”;
         public ClientAssertionCertificate Certificate { get; set; }

        public X509Certificate2 FindCertificateByThumbprint()
         {
             X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
             store.Open(OpenFlags.ReadOnly);
             X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint, Thumbprint, false);
             store.Close();

            if (col == null || col.Count == 0)
                 throw new Exception(“ERROR: Certificate not found with thumbprint”);

            return col[0];
         }

        public void GetCertificate()
         {
             var clientAssertionCertPfx = FindCertificateByThumbprint();
             Certificate = new ClientAssertionCertificate(ClientID, clientAssertionCertPfx);
         }
         public async Task<string> GetAccessToken(string authority, string resource, string scope)
         {
             var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
             var result = await context.AcquireTokenAsync(resource, Certificate);

            return result.AccessToken;
         }

        public string GetKeyVaultSecret(string secretNode)
         {
             var secretUri = string.Format(“{0}{1}”, VaultURL + “secrets/”, secretNode);
             GetCertificate();
             var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessToken));

            return keyVaultClient.GetSecretAsync(secretUri).Result.Value;
         }
     }
}

Deploy the Application

Publish the application to the same App Service we created in previous step.

Article Series

This post is part of an Article Series:

Azure Certificate based Authentication from App Service to Access Key Vault

One thought on “Create Web API Project to Access Certificate & Key Vault Secret

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s