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

Azure Key Vault & Access from C#

Azure Key Vault & Access from C#

In this article we can explore how to create an Azure Key Vault & Access from C#.

Azure Key Vault

Azure Key Vault allows to keep encrypted secured strings. Eg: Connection Strings, Passwords etc.

Create Azure Key Vault

Open Azure Portal & Create a new Key Vault as shown below.

image

Go the Secrets blade and create a new Secret with name as key1 and value as value1

image

Create App Registration

We need to create an App Registration for our Console Application. This will enable to Authenticate our Console Application using the Credentials.

Go to Azure Portal > Azure Active Directory > App Registrations. Create new App Registration as below.

image

Create new client secret too.

image

Now copy the Client ID and Client Secret which you need in the next steps.

Authorize Console Application

We need to Authorize the Console Application to the Key Vault. Without this step you will get Forbidden error.

Go to Key Vault > Access Policies blade

image

Click Add Access Policy and select our Console Application as Principal.

image

image

Now onwards any application authenticated through Client Credentials of the Console App Registration will be considered as Principal – which is the Security Identity for the application.

Create Project

Create a new console application in Visual Studio. Add references to following:

· Microsoft.Azure.KeyVault

· Microsoft.IdentityModel.Clients.ActiveDirectory

Replace the code with following.

using Microsoft.Azure.KeyVault;

using Microsoft.IdentityModel.Clients.ActiveDirectory;

using System;

using System.Threading.Tasks;

namespace KeyVault

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine($”Secret Value from Vault is: {GetVaultValue()}”);

Console.ReadKey(false);

}

static string GetVaultValue()

{

KeyVaultClient client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));

var vaultAddress = “https://your-key-vault.vault.azure.net&#8221;;

var secretName = “key1”;

var secret = client.GetSecretAsync(vaultAddress, secretName).GetAwaiter().GetResult();

return secret.Value;

}

static async Task GetToken(string authority, string resource, string scope)

{

var clientId = “YOUR CLIENT ID”;

var clientSecret = “YOUR CLIENT SECRET”;

ClientCredential credential = new ClientCredential(clientId, clientSecret);

var context = new AuthenticationContext(authority, TokenCache.DefaultShared);

var result = await context.AcquireTokenAsync(resource, credential);

return result.AccessToken;

}

}

}

On running the application, you will get the following output.

image

References

Create Key Vault & Secret

Summary

In this article we have explored how to create an Azure Key Vault & Access from C#.