53 lines
		
	
	
		
			2.1 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			53 lines
		
	
	
		
			2.1 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
| using Azure.Identity;
 | |
| using Azure.Security.KeyVault.Secrets;
 | |
| using Microsoft.Extensions.Configuration;
 | |
| using Microsoft.Extensions.DependencyInjection;
 | |
| 
 | |
| namespace Core.Blueprint.KeyVault.Configuration
 | |
| {
 | |
|     /// <summary>
 | |
|     /// Registers the SecretClient for Azure Key Vault as a singleton service.
 | |
|     /// </summary>
 | |
|     /// <param name="services">The IServiceCollection to add the services to.</param>
 | |
|     /// <param name="configuration">The application's configuration.</param>
 | |
|     /// <returns>The updated IServiceCollection.</returns>
 | |
|     /// <exception cref="ArgumentNullException">Thrown when the KeyVault URI is missing in the configuration.</exception>
 | |
|     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<VaultOptions>();
 | |
| 
 | |
|                 if (string.IsNullOrEmpty(vaultSettings?.Address) || string.IsNullOrEmpty(vaultSettings.Token)
 | |
|                     || 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<IKeyVaultProvider, KeyVaultProvider>();
 | |
|             return services;
 | |
|         }
 | |
|     }
 | |
| }
 |