15 August 2023

How to create Azure Key Vault and how to get secret key using a C# console application from local computer?

This tutorial is for beginners and especially for those who have no idea about Azure Key Vault.

In this tutorial I will explain how to create an Azure Key Vault and how we can fetch Azure Key Vault data on local computer using C# console application.

The minimum requirement is to follow the steps by yourself
  1. Need an Azure Account.
  2. Visual Studio / Visual Studio Code.
  3. C# Knowledge (Beginner level).
Step 1:  Log in to azure account and Search for Azure Key Vault and Create a new Key Vault.
Select Vault access policy true.
Step 2: Create a secret by clicking on the + Generate/Import button.
Set activation and expiration date is an optional, enter secret name and secret value.
Step 3: Now go to Azure AD and create an app registration and in the api permission section add azure key vault permission and then add a secret (Keep the secrect value with you because it will only show at the time of creation).
Step 4: Now go back to the Key Vault (“MSDynamicCESecretKey”) again and create access policy and set secret permissions as Get in the Azure Key Vault and select the principal.
Step 5: Create a c# console application.

using System;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
class Program
{
    static void Main(string[] args)
    {
        string keyVaultUrl = "https://msdynamiccesecretkey.vault.azure.net/";
        string secretName = "SecretKey";

        //Get TenantId, ClientId and  ClientSecret From AD App registration
        string tenantId = "a8eaa793-754b-4d21-9e60-a882c97f7bab";
        string clientId = "209b0d23-0f28-452a-b971-4e316bc3f5b8";
        string clientSecret = "***************************";

        var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);
        var secretClient = new SecretClient(new Uri(keyVaultUrl), clientSecretCredential);
        
        KeyVaultSecret secret = secretClient.GetSecret(secretName);

        Console.WriteLine($"The key vault Secret value is : {secret.Value}");
        Console.ReadLine();
    }
}

// The code mentioned above is the simplest code that only shows how to get the secret value from the Azure Key vault.

No comments:

Post a Comment

What is Azure Storage Queue and how to Create Azure Storage Queue message using C# console application.

Azure Storage Queue is a component of Azure Storage Account which is used for messaging service.  We can Add message to a Queue and also deq...