Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Program
- {
- private const string APP_NAME = "5E71EE95-49BD-40A9-81CD-B1DFD873EEA8";
- private const string SECRET_CONFIG_FILE_NAME = "appsettings.secret.json";
- public static void Main(string[] args)
- {
- if (args != null && args.Length == 1 && args[0].ToLowerInvariant() == "-config")
- {
- ConfigAppSettingsSecret();
- return;
- }
- CreateWebHostBuilder(args).Build().Run();
- }
- public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
- WebHost.CreateDefaultBuilder(args)
- .ConfigureAppConfiguration((builder, options) =>
- {
- options.AddJsonFile(ConfigFileFullPath, optional: true, reloadOnChange: false);
- })
- .UseStartup<Startup>();
- private static void ConfigAppSettingsSecret()
- {
- var serviceCollection = new ServiceCollection();
- AddDataProtection(serviceCollection);
- var services = serviceCollection.BuildServiceProvider();
- var dataProtectionProvider = services.GetService<IDataProtectionProvider>();
- var protector = CreateProtector(dataProtectionProvider);
- string dbPassword = protector.Protect("DbPassword", ReadPasswordFromConsole());
- ... // other secrets
- string json = ...; // Serialize encrypted secrets to JSON
- var path = ConfigFileFullPath;
- File.WriteAllText(path, json);
- Console.WriteLine($"Writing app settings secret to '${path}' completed successfully.");
- }
- private static string CurrentDirectory
- {
- get { return Directory.GetParent(typeof(Program).Assembly.Location).FullName; }
- }
- private static string ConfigFileFullPath
- {
- get { return Path.Combine(CurrentDirectory, SECRET_CONFIG_FILE_NAME); }
- }
- internal static void AddDataProtection(IServiceCollection serviceCollection)
- {
- serviceCollection.AddDataProtection()
- .SetApplicationName(APP_NAME)
- .DisableAutomaticKeyGeneration();
- }
- internal static IDataProtector CreateProtector(IDataProtectionProvider dataProtectionProvider)
- {
- return dataProtectionProvider.CreateProtector(APP_NAME);
- }
- }
- public void ConfigureServices(IServiceCollection services)
- {
- Program.AddDataProtection(services);
- ...
- }
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- ...
- if (env.IsProduction())
- {
- var dataProtectionProvider = app.ApplicationServices.GetService<IDataProtectionProvider>();
- var protector = Program.CreateProtector(dataProtectionProvider);
- var builder = new SqlConnectionStringBuilder();
- builder.Password = protector.Unprotect(configuration["DbPassword"]);
- ...
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement