Last active
April 26, 2020 04:54
-
-
Save finesse-fingers/c09f37b5ed6b483606b342f11cc3198f to your computer and use it in GitHub Desktop.
Azure keyvault prefix manager and usage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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