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
- dotnet add package Microsoft.Extensions.Azure
- 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"
}
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"));
});
Create an Interface for Dependency Injection
Create an interface which can help us in injecting the dependency.
builder.Services.AddSingleton<IKeyVaultManager, KeyVaultManager>();
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);
}
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;
}
}
}
}
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 (0)