Created
June 25, 2021 01:09
-
-
Save MahdiKarimipour/33411a1dbd5127e3ef0458ffd385660d to your computer and use it in GitHub Desktop.
App Secrets Load at Start Up Time
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 IHostBuilder CreateHostBuilder(string[] args) => | |
Host.CreateDefaultBuilder(args) | |
.ConfigureWebHostDefaults(webBuilder => | |
{ | |
webBuilder.UseStartup<Startup>(); | |
}) | |
.ConfigureAppConfiguration((context, config) => | |
{ | |
if (context.HostingEnvironment.IsProduction()) | |
{ | |
var builtConfig = config.SetBasePath(Directory.GetCurrentDirectory()) | |
.AddJsonFile("appsettings.json", false) | |
.AddJsonFile($"appsettings.Production.json", true) | |
.AddEnvironmentVariables() | |
.Build(); | |
var settings = builtConfig.GetSection("AppSettings").Get<AppSettings>(); | |
using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) | |
{ | |
store.Open(OpenFlags.ReadOnly); | |
var allCerts = store.Certificates; | |
var certs = allCerts | |
.Find(X509FindType.FindByThumbprint, | |
settings.AzureKeyVaultSettings.AzureADCertThumbprint, false); | |
config.AddAzureKeyVault(new Uri($"https://{settings.AzureKeyVaultSettings.KeyVaultName}.vault.azure.net/"), | |
new ClientCertificateCredential( | |
settings.AzureKeyVaultSettings.AzureADDirectoryId, | |
settings.AzureKeyVaultSettings.AzureADApplicationId, | |
certs.OfType<X509Certificate2>().Single())); | |
store.Close(); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment