Accessing Azure Key Vault using C#

How to access key vault using C# ?

There are two types of authentication to access key vault resources

  • Access through the service principal / Active directory user
  • Access through the Active Directory Application

Step 1 

Create an Active directory APP on azure.
  1. Login to Azure account and navigate to Azure Active Directory from menu.
  2. Click on App registrations
  3. Click on (+ icon) New Application Registration
  4. Fill in Application Name , Application Type - Web App/API and URL (any dummy url or your application URL)
  5. Click on create.
  6. Once the app is created navigate to the app and click on settings and click on Keys. You can generated new key and keep that safe for use further in your C# code.

Step 2

Create Key Vault on Azure

You can create key vault on azure from azure portal

You can also use PowerShell to create the keyvault 

Now navigate to access policies and click on new. Provide necessary access to the newly created app.
Once you have completed the above steps then final step is to write the C# code for KeyVault secret access. 
Create a C# console application and add the below NuGet packages.

We will create the KeyVaultHandler Class as below.


using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Neudesic.KeyVaultManager
{
    public class KeyVaultHandler
    {
        private string vaultUrl;
        private string clientId;
        private string clientSecret;
        private KeyVaultClient keyVaultClient;


        public KeyVaultHandler(string vaultUrl, string clientId, string clientSecret)
        {
            this.vaultUrl = vaultUrl;
            this.clientId = clientId;
            this.clientSecret = clientSecret;
            keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(
             (authority, resource, scope) => GetAccessToken(authority, resource, scope)));
        }
        public KeyVaultHandler()
        {
            this.vaultUrl = ConfigHelper.GetConfigurationValue("VaultUrl");
            this.clientId = ConfigHelper.GetConfigurationValue("ClientId");
            this.clientSecret = ConfigHelper.GetConfigurationValue("ClientSecret");
        }
        public async Task<string> GetAccessToken(string authority, string resource, string scope)
        {
            var clientCredential = new ClientCredential(clientId, clientSecret);
            var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
            var result = await context.AcquireTokenAsync(resource, clientCredential).ConfigureAwait(false);
            return result.AccessToken;
        }
        /// <summary>
        /// Retrieve keyvault secret value
        /// </summary>
        /// <param name="secretName">KeyVault secret name</param>
        /// <returns>KeyValut Secret value</returns>
        public string GetSecret(string secretName)
        {
            try
            {
                return keyVaultClient.GetSecretAsync(vaultUrl, secretName).GetAwaiter().GetResult()?.Value;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// Creates KeyVault Key
        /// </summary>
        /// <param name="KeyName">KeyVault Key Name</param>
        /// <param name="KeyType">KeyVault Key Type - (RSA,EC)</param>
        /// <param name="Size">KeyVault Key Size - (2048,3072,4096)</param>
        public void CreateKeyVaultKey(string KeyName, string KeyType,int? Size)
        {
           keyVaultClient.CreateKeyAsync(vaultUrl, KeyName, KeyType, Size).GetAwaiter().GetResult();
        }

        public void ImportKeyVaultKey()
        {
            //keyVaultClient.ImportKeyAsync()
        }

        public string GetKeyVaultKey(string key)
        {
            return keyVaultClient.GetKeyAsync(vaultUrl,key).GetAwaiter().GetResult().KeyIdentifier.Identifier;
        }

        public List<string> GetAllSecrets(List<string> secretsName)
        {
            List<string> data = new List<string>();
            
            return data;
        }
    }
}


Code to use KeyVault Class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Neudesic.KeyVaultManager;

namespace KeyVaultManagerApp
{
    class Program
    {
        public const string ClientID = "<ApplicationID created by you in AAD>";
        public const string VaultUrl = "Key Vault URL";
        public const string ClientSecret = "Secret key for AAD Application";

        static void Main(string[] args)
        {
            KeyVaultHandler keyVaultHandler = new KeyVaultHandler(VaultUrl, ClientID, ClientSecret);
            Console.WriteLine(keyVaultHandler.GetKeyVaultKey("test"));
            //keyVaultHandler.CreateKeyVaultKey("test", "RSA", 2048);

        }
    }
}




No comments:

Post a Comment

T-SQL LEAD LAG and SUM function based query

  Query on T-SQL window clause Below is the sales table Order_Date Name Product SubCategory ...