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;

             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 = “”;
         public ClientAssertionCertificate Certificate { get; set; }

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

            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);
             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