Skip to content

Instantly share code, notes, and snippets.

@finesse-fingers
Last active April 26, 2020 04:54
Show Gist options
  • Save finesse-fingers/c09f37b5ed6b483606b342f11cc3198f to your computer and use it in GitHub Desktop.
Save finesse-fingers/c09f37b5ed6b483606b342f11cc3198f to your computer and use it in GitHub Desktop.
Azure keyvault prefix manager and usage
using Microsoft.Azure.KeyVault.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.AzureKeyVault;
namespace Demo.Azure.KeyVault
{
public class PrefixKeyVaultSecretManager : IKeyVaultSecretManager
{
private readonly string _prefix;
public PrefixKeyVaultSecretManager(string prefix)
{
_prefix = $"{prefix}-".ToLowerInvariant();
}
public bool Load(SecretItem secret)
{
return secret.Identifier.Name.StartsWith(_prefix);
}
public string GetKey(SecretBundle secret)
{
return secret.SecretIdentifier.Name
.Substring(_prefix.Length)
.Replace("--", ConfigurationPath.KeyDelimiter);
}
}
}
public static class ServiceExtensions
{
/// <summary>
/// Creates a custom configuration for easier development of Azure Functions.
/// When environment is not Development, it adds a keyvault provider
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static IConfiguration GetCustomConfiguration(this IFunctionsHostBuilder builder)
{
IConfiguration localConfiguration;
if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
{
localConfiguration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build() as IConfiguration;
}
else
{
var rootConfig = builder.Services.BuildServiceProvider().GetRequiredService<IConfiguration>();
var keyVaultBaseUrl = rootConfig.GetValue<string>("KeyVaultBaseUrl");
// add keyvault
localConfiguration = new ConfigurationBuilder()
.AddAzureKeyVault(keyVaultBaseUrl, new PrefixKeyVaultSecretManager("prefix"))
.AddEnvironmentVariables()
.Build() as IConfiguration;
// we have to replace the rootConfig with the new one that has keyVault
builder.Services.AddSingleton(localConfiguration);
}
return localConfiguration;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment