Wednesday, 14 June 2023

Create, access and delete secrets in Azure Key Vault using C# console app

 In this article, I explained how to create, access and delete secrets in Azure Key Vault using C# console app.


  • Azure key Vault:

Azure Key Vault is a cloud service that provides a secure store for secrets. You can securely store keys, passwords, certificates, and other secrets. Azure key vaults may be created and managed through the Azure portal.

 

  • Advantage:

  1.          Using Azure Key Vault to store application secrets centrally, you can regulate how they’re distributed. Secrets are much less likely to be mistakenly revealed using Key Vault.
  2.        . When using Key Vault, application developers no longer need to store security information in their applications. The necessity to make security information part of the code is eliminated by not needing to store security information in apps.
  3.        . For example, an application would need to connect to a database. Instead of storing the connection string in the app’s code, you can safely save it in Key Vault. URIs allow your applications to safely access the data they require.

 

  • Define variables.

const string KEYVALUTNAME = "testkeyvault"; // Set this to the name of your key vault

static string keyVaultUri = $"https://{KEYVALUTNAME}.vault.azure.net";

static SecretClient secretClient = null;

 

 

  • Define a method to list all the secret you have in your azure key vault.

private static void ListAllSecrets()

        {

            Console.WriteLine("All Secrets:");

            var allSecrets = secretClient.GetPropertiesOfSecrets();

            foreach (var secret in allSecrets)

            {

                var secretValue = secretClient.GetSecret(secret.Name);

                Console.WriteLine($"{secret.Name} | {secretValue.Value.Value} | {secretValue.Value.Properties.ContentType}");

            }

            Console.WriteLine();

        }

 

  • Code to create secret:

            Console.Write("Input the Secret name to set (ENTER to skip):");

            var setSecretName = Console.ReadLine();

            if (setSecretName != "")

            {

                Console.Write("Input the Secret value to set:");

                var setSecretValue = Console.ReadLine();

 

                Console.WriteLine("Setting secret...");

                await secretClient.SetSecretAsync(setSecretName, setSecretValue);

                Console.WriteLine($"Secret {setSecretName} set to {setSecretValue}!");

 

                // Set content type

                var secret = secretClient.GetSecret(setSecretName);

                secret.Value.Properties.ContentType = "Demo Type";

                secretClient.UpdateSecretProperties(secret.Value.Properties);

            }

 

 

  • Code to soft delete the secrets:

            Console.Write("Input a Secret Name to soft delete (ENTER to skip):");

            var deleteSecretName = Console.ReadLine();

            if (deleteSecretName != "")

            {

                var operation = secretClient.StartDeleteSecret(deleteSecretName);

                Console.Write($"Deleting secret {deleteSecretName}...");

                while (!operation.HasCompleted)

                {

                    Thread.Sleep(1000);

                    Console.Write($".");

                    operation.UpdateStatus();

                }

                Console.WriteLine();

                Console.WriteLine($"Secret {deleteSecretName} deleted!");

            }

 

  • Code to permanently delete the secrets:

            Console.Write("Input a Secret Name to permanently delete (ENTER to skip):");

            var purgeSecretName = Console.ReadLine();

            if (purgeSecretName != "")

            {

                var operation = secretClient.StartDeleteSecret(purgeSecretName);

                Console.Write($"Soft deleting secret {purgeSecretName}...");

                while (!operation.HasCompleted)

                {

                    Thread.Sleep(1000);

                    Console.Write($".");

                    operation.UpdateStatus();

                }

                Console.WriteLine();

                Console.WriteLine($"Secret {purgeSecretName} deleted!");

                secretClient.PurgeDeletedSecret(purgeSecretName);

                Console.WriteLine($"Secret {purgeSecretName} purged!");

            }

 

  • Complete code example:

using System;

using System.Threading;

using System.Threading.Tasks;

using Azure.Identity;

using Azure.Security.KeyVault.Secrets;

 

namespace AzManageKeyVaultSecrets

{

    internal class Program

    {

        const string KEYVALUTNAME = "dgtestkeyvault"; // Set this to the name of your key vault

        static string keyVaultUri = $"https://{KEYVALUTNAME}.vault.azure.net";

        static SecretClient secretClient = null;

        static async Task Main(string[] args)

        {

            var credentials = new DefaultAzureCredential();

            secretClient = new SecretClient(new Uri(keyVaultUri), credentials);

 // First call the ListAllSecrets method to dislay all secrets

              ListAllSecrets();

            Console.Write("Input the Secret name to set (ENTER to skip):");

            var setSecretName = Console.ReadLine();

            if (setSecretName != "")

            {

                Console.Write("Input the Secret value to set:");

                var setSecretValue = Console.ReadLine();

 

                Console.WriteLine("Setting secret...");

                await secretClient.SetSecretAsync(setSecretName, setSecretValue);

                Console.WriteLine($"Secret {setSecretName} set to {setSecretValue}!");

 

                // Set content type

                var secret = secretClient.GetSecret(setSecretName);

                secret.Value.Properties.ContentType = "Demo Type";

                secretClient.UpdateSecretProperties(secret.Value.Properties);

            }

 

            Console.Write("Input a Secret Name to soft delete (ENTER to skip):");

            var deleteSecretName = Console.ReadLine();

            if (deleteSecretName != "")

            {

                var operation = secretClient.StartDeleteSecret(deleteSecretName);

                Console.Write($"Deleting secret {deleteSecretName}...");

                while (!operation.HasCompleted)

                {

                    Thread.Sleep(1000);

                    Console.Write($".");

                    operation.UpdateStatus();

                }

                Console.WriteLine();

                Console.WriteLine($"Secret {deleteSecretName} deleted!");

            }

 

            Console.Write("Input a Secret Name to permanently delete (ENTER to skip):");

            var purgeSecretName = Console.ReadLine();

            if (purgeSecretName != "")

            {

                var operation = secretClient.StartDeleteSecret(purgeSecretName);

                Console.Write($"Soft deleting secret {purgeSecretName}...");

                while (!operation.HasCompleted)

                {

                    Thread.Sleep(1000);

                    Console.Write($".");

                    operation.UpdateStatus();

                }

                Console.WriteLine();

                Console.WriteLine($"Secret {purgeSecretName} deleted!");

                secretClient.PurgeDeletedSecret(purgeSecretName);

                Console.WriteLine($"Secret {purgeSecretName} purged!");

            }

 

            ListAllSecrets();

 

            Console.WriteLine();

            Console.WriteLine("Done!");

        }

 

        private static void ListAllSecrets()

        {

            Console.WriteLine("All Secrets:");

            var allSecrets = secretClient.GetPropertiesOfSecrets();

            foreach (var secret in allSecrets)

            {

                var secretValue = secretClient.GetSecret(secret.Name);

                Console.WriteLine($"{secret.Name} | {secretValue.Value.Value} | {secretValue.Value.Properties.ContentType}");

            }

            Console.WriteLine();

 

        }

    }

}




Please feel free to ask if any doubts.

No comments:

Post a Comment