DEV Community

Ishwar398
Ishwar398

Posted on

Azure Key Vault with .NET - Reading & Writing secrets from a C# application

Once you have created a Key Vault resource, and you've set the Access Policies, the next step is to establish a connection between the application and Key Vault to perform operations like reading, writing and deleting values from Key Vault.

Install the required Nuget Packages

  1. dotnet add package Microsoft.Extensions.Azure
  2. dotnet add package Azure.Security.KeyVault.Secrets

Setup the appsettings file

  • In the Overview page of the Key Vault resource in Azure portal, copy the VaultURI.
  • Add a section in the appsettings file or the config file.
"KeyVault": {
    "VaultUri": "VAULT-URI"
  }
Enter fullscreen mode Exit fullscreen mode

Adding the KeyVault service

  • In the ConfigureServices method, we need to configure our KeyVault connection
  • In WebApp this will be present in the Program.cs, in Console Application it will be present in the StartUp.cs
builder.Services.AddAzureClients(azureClientFactoryBuilder =>
{

    azureClientFactoryBuilder.AddSecretClient(

    Configuration.GetSection("KeyVault"));

});
Enter fullscreen mode Exit fullscreen mode

Create an Interface for Dependency Injection

Create an interface which can help us in injecting the dependency.

builder.Services.AddSingleton<IKeyVaultManager, KeyVaultManager>();
Enter fullscreen mode Exit fullscreen mode

Add three classes to Write, Read and Delete a secret from KeyVault

public interface IKeyVaultManager
    {
        public Task<bool> WriteSecret(string key,string secret);
        public Task<string> ReadSecret(string key);
        public Task<bool> DeleteSecret(string key);
    }
Enter fullscreen mode Exit fullscreen mode

Setup the class for the interface

Using the interface above, create a class and inherit it from the above interface and implement the three methods in the class.

using Azure.Security.KeyVault.Secrets;

namespace KeyVaultConnectivity.KeyVault
{
    public class KeyVaultManager: IKeyVaultManager
    {
        public SecretClient SecretClient { get; set; }

        public KeyVaultManager(SecretClient secretClient)
        {
            SecretClient = secretClient;
        }

        public async Task<bool> WriteSecret(string key, string secret)
        {
            try
            {
                await SecretClient.SetSecretAsync(key,secret);
                return true;
            }
            catch(Exception ex)
            {
                //Log the exception
                Console.WriteLine(ex.Message);
                return false;
            }
        }

        public async Task<string?> ReadSecret(string key)
        {
            try
            {
                var secret = await SecretClient.GetSecretAsync(key);
                return secret != null ? secret.Value.ToString() : string.Empty;
            }
            catch (Exception ex)
            {
                //Log the exception
                Console.WriteLine(ex.Message);
                return string.Empty;
            }
        }

        public async Task<bool> DeleteSecret(string key)
        {
            try
            {
                await SecretClient.StartDeleteSecretAsync(key);
                return true;
            }
            catch (Exception ex)
            {
                //Log the exception
                Console.WriteLine(ex.Message);
                return false;
            }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Using this service

Inject the service in the class which has to read secrets from Key Vault and the respective method from the class.

Top comments (1)

Collapse
 
manu_vr profile image
Manu Radhakrishnan

Is there any option for Mocking the EncryptAsync() in Azure.Security.KeyVault.Keys.Cryptography.

dev.to/manu_vr/how-to-mock-encrypt...