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.

Image of AssemblyAI tool

Challenge Submission: SpeechCraft - AI-Powered Speech Analysis for Better Communication

SpeechCraft is an advanced real-time speech analytics platform that transforms spoken words into actionable insights. Using cutting-edge AI technology from AssemblyAI, it provides instant transcription while analyzing multiple dimensions of speech performance.

Read full post

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...

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay