using Azure.Identity; using Azure.Security.KeyVault.Secrets; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Core.Blueprint.KeyVault.Configuration { /// /// Registers the SecretClient for Azure Key Vault as a singleton service. /// /// The IServiceCollection to add the services to. /// The application's configuration. /// The updated IServiceCollection. /// Thrown when the KeyVault URI is missing in the configuration. public static class RegisterBlueprint { public static IServiceCollection AddKeyVault(this IServiceCollection services, IConfiguration configuration) { var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty; if(environment == "Local") { var vaultSettings = configuration.GetSection("Vault").Get(); if (string.IsNullOrEmpty(vaultSettings?.Address) || string.IsNullOrEmpty(vaultSettings.Token) || string.IsNullOrEmpty(vaultSettings?.SecretPath) || string.IsNullOrEmpty(vaultSettings.SecretMount)) { throw new ArgumentNullException("Vault options are not configured correctly."); } services.AddSingleton(vaultSettings); } else { var keyVaultUriString = configuration["ConnectionStrings:KeyVaultDAL"]; if (string.IsNullOrEmpty(keyVaultUriString)) { throw new ArgumentNullException("ConnectionStrings:KeyVault", "KeyVault URI is missing in the configuration."); } var keyVaultUri = new Uri(keyVaultUriString); services.AddSingleton(_ => new SecretClient(keyVaultUri, new DefaultAzureCredential())); } services.AddSingleton(); return services; } } }