Skip to content

Instantly share code, notes, and snippets.

@agehlot
Created March 13, 2021 18:25
Show Gist options
  • Save agehlot/460697d404d0e407d95cbb22d916e8d3 to your computer and use it in GitHub Desktop.
Save agehlot/460697d404d0e407d95cbb22d916e8d3 to your computer and use it in GitHub Desktop.
Helper methods for getting a key from Azure Key Vault
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.KeyVault.Models;
using Microsoft.Identity.Client;
using Sitecore.Diagnostics;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Configuration;
namespace Core.Foundation.AzureKeyVault.Helper
{
public static class AzureKeyVaultCacheHelper
{
#region Properties
public static string BaseUri { get; set; }
public static string ClientId { get; set; }
public static string ClientSecret { get; set; }
private static KeyVaultClient _KeyVaultClient = null;
private static Dictionary<string, string> SecretsCache = new Dictionary<string, string>();
#endregion
#region Static Constructure
static AzureKeyVaultCacheHelper()
{
BaseUri = WebConfigurationManager.AppSettings["AzureKeyVault-BaseUrl"];
ClientId = WebConfigurationManager.AppSettings["AzureKeyVault-ClientId"];
ClientSecret = WebConfigurationManager.AppSettings["AzureKeyVault-ClientSecret"];
}
#endregion
public static string GetCachedSecret(string secretName)
{
var value = string.Empty;
try
{
value = GetCachedSecretAsync(secretName).Result;
Log.Info($"AzureKeyVaultCacheHelper.GetCachedSecret({secretName}:{value})", typeof(AzureKeyVaultCacheHelper));
}
catch (System.Exception ex)
{
Log.Warn($"AzureKeyVaultCacheHelper: Not able to connect to Azure KeyVault: " + ex, new object());
}
return value;
}
public static async Task<string> GetCachedSecretAsync(string secretName)
{
if (!SecretsCache.ContainsKey(secretName))
{
if (_KeyVaultClient is null)
{
_KeyVaultClient = new KeyVaultClient(async (authority, resource, scope) =>
{
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(ClientId)
.WithClientSecret(ClientSecret)
.WithAuthority(authority)
.Build();
AuthenticationResult authenticationResult = await confidentialClientApplication
.AcquireTokenForClient(new string[] { "https://vault.azure.net/.default" })
.ExecuteAsync();
return authenticationResult.AccessToken;
});
Log.Info($"GetCachedSecretAsync._KeyVaultClient was null, Created new instance.", typeof(AzureKeyVaultCacheHelper));
}
try
{
var secretBundle = await _KeyVaultClient.GetSecretAsync($"{BaseUri}{secretName}").ConfigureAwait(false);
SecretsCache.Add(secretName, secretBundle.Value);
}
catch (KeyVaultErrorException kvex)
{
Log.Error($"Message:{kvex.Message}, URL:{BaseUri}{secretName}, StackTrace:{kvex.StackTrace}", typeof(AzureKeyVaultCacheHelper));
}
catch (System.Exception ex)
{
Log.Error($"Message:{ex.Message}, URL:{BaseUri}{secretName}, StackTrace:{ex.StackTrace}", typeof(AzureKeyVaultCacheHelper));
}
}
var keyValue = SecretsCache.ContainsKey(secretName) ? SecretsCache[secretName] : string.Empty;
if (string.IsNullOrEmpty(keyValue)) Log.Info($"GetCachedSecretAsync. Key {secretName} not found in keyvault dictionary. Default will be used.", typeof(AzureKeyVaultCacheHelper));
return keyValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment