Dear developers new to Azure Key Vault, if you want to retrieve secrets from the Azure environment, you're in the right place. Without wasting any time, I'll explain the steps to you, step by step.
Step 1 :- Hopefully, you know how to create a Key Vault. If not, here’s how to do it: quick
Step 2 :- You need to configure the URL in your appsetting file : https://contoso-vault2.vault.azure.net/
Note:- Kindly use your Azure Key Vault URL, and make sure to apply your development settings in the local environment.
appsettings.json
"Setting": {
"EnableKeyVaultCache": true,
"KeyVaultUri": "https://test.vault.azure.net/",
},
Create Interface
public interface IKeyVaultService
{
string GetSecret(string secretName);
Task<(string, bool)> TryGetSecretAsync(string secretName);
}
Service code:-
namespace KeyVault
{
public class KeyVaultService : IKeyVaultService
{
private readonly bool _enableCache = false;
private readonly string _uri;
private readonly IDictionary<string, string> _table = new Dictionary<string, string>();
public KeyVaultService(IConfiguration config)
{
_enableCache = config.GetValue<bool>("Setting:EnableKeyVaultCache");
_uri = config.GetValue<string>("Setting:KeyVaultUri");
}
/// <summary>
/// Get secret value from Azure Key Vault.
/// </summary>
/// <param name="secretName"></param>
/// <returns></returns>
public string GetSecret(string secretName)
{
if (_enableCache && _table.ContainsKey(secretName))
{
return _table[secretName];
}
else
{
var client = new SecretClient(new Uri(_uri), new DefaultAzureCredential());
var secret = client.GetSecretAsync(secretName).GetAwaiter().GetResult().Value;
if (_enableCache)
{
_table.Add(secretName, secret.Value);
}
return secret.Value;
}
}
/// <summary>
/// Tries to read a secret's value from Azure Key Vault with that secret's name.
/// </summary>
/// <param name="secretName"></param>
/// <remarks>
/// This method does not throw exception when a secret does not exist in Key Vault.
/// </remarks>
/// <returns>
/// This method returns a tuple which includes an boolean value and a string.
/// When there's no exception, the boolean value is true;
/// otherwise the boolean value is false.
/// </returns>
public async Task<(string, bool)> TryGetSecretAsync(string secretName)
{
try
{
if (_enableCache && _table.ContainsKey(secretName))
{
return (_table[secretName], true);
}
else
{
var client = new SecretClient(new Uri(_uri), new DefaultAzureCredential());
var secret = await client.GetSecretAsync(secretName);
string secretValue = secret.Value.Value;
if (_enableCache)
{
_table[secretName] = secretValue;
}
return (secretValue, true);
}
}
catch (Exception e)
{
ExceptionManager.HandleException(e);
return (null, false);
}
}
}
}
No comments:
Post a Comment