Exemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StartupCommon"/> class.
        /// </summary>
        public StartupCommon()
        {
            var builder = new ConfigurationBuilder()
                          .AddJsonFile("appsettings.json")
                          .AddEnvironmentVariables();

            var config = builder.Build();
            AzureKeyVaultConfigurationOptions azureKeyVaultConfigurationOptions = new AzureKeyVaultConfigurationOptions(
                config["KeyVaultUrl"])
            {
                ReloadInterval = TimeSpan.FromSeconds(double.Parse(config[Constants.KeyVaultConfigRefreshDurationSeconds], CultureInfo.InvariantCulture)),
            };

            _ = builder.AddAzureKeyVault(azureKeyVaultConfigurationOptions);

            this.Configuration = builder.Build();

            _ = builder.AddAzureAppConfiguration(options =>
            {
                var settings = options.Connect(this.Configuration["AzureAppConfigConnectionstring"]).Select(KeyFilter.Any, "Common")
                               .Select(KeyFilter.Any, "Service")
                               .Select(KeyFilter.Any, "Handler");
                _ = settings.ConfigureRefresh(refreshOptions =>
                {
                    _ = refreshOptions.Register(key: this.Configuration["AppConfig:ForceRefresh"], refreshAll: true, label: LabelFilter.Null);
                });
            });

            this.Configuration = builder.Build();
        }
Exemplo n.º 2
0
        /// <summary>
        /// Adds Azure Key Vault as a Configuration Source.
        /// </summary>
        /// <param name="builder">The web host builder to configure.</param>
        /// <returns>The web host builder.</returns>
        public static IHostBuilder AddOrchardCoreAzureKeyVault(this IHostBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            builder.ConfigureAppConfiguration((context, configuration) =>
            {
                var builtConfig  = configuration.Build();
                var keyVaultName = builtConfig["OrchardCore:OrchardCore_KeyVault_Azure:KeyVaultName"];

                TimeSpan?reloadInterval = null;
                double interval;
                if (Double.TryParse(builtConfig["OrchardCore:OrchardCore_KeyVault_Azure:ReloadInterval"], out interval))
                {
                    reloadInterval = TimeSpan.FromSeconds(interval);
                }

                var keyVaultEndpointUri = new Uri("https://" + keyVaultName + ".vault.azure.net");
                var configOptions       = new AzureKeyVaultConfigurationOptions()
                {
                    Manager        = new AzureKeyVaultSecretManager(),
                    ReloadInterval = reloadInterval
                };

                configuration.AddAzureKeyVault(
                    keyVaultEndpointUri,
                    new DefaultAzureCredential(includeInteractiveCredentials: true),
                    configOptions
                    );
            });

            return(builder);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StartupCommon"/> class.
        /// </summary>
        /// <param name="application">service/application name (Handler, Service).</param>
        public StartupCommon(string application)
        {
            var builder = new ConfigurationBuilder()
                          .AddJsonFile("appsettings.json")
                          .AddEnvironmentVariables();

            var config = builder.Build();
            AzureKeyVaultConfigurationOptions azureKeyVaultConfigurationOptions = new AzureKeyVaultConfigurationOptions(
                config[ConfigConstants.KeyVaultUrlConfigKey])
            {
                ReloadInterval = TimeSpan.FromSeconds(double.Parse(config[ConfigConstants.KeyVaultConfigRefreshDurationSeconds], CultureInfo.InvariantCulture)),
            };

            _ = builder.AddAzureKeyVault(azureKeyVaultConfigurationOptions);

            this.Configuration = builder.Build();

            _ = builder.AddAzureAppConfiguration(options =>
            {
                var settings = options.Connect(this.Configuration[ConfigConstants.AzureAppConfigConnectionstringConfigKey]).Select(KeyFilter.Any, "Common")
                               .Select(KeyFilter.Any, application);
                _ = settings.ConfigureRefresh(refreshOptions =>
                {
                    _ = refreshOptions.Register(ConfigConstants.ForceRefreshConfigKey, "Common", refreshAll: true);
                });
            });

            this.Configuration = builder.Build();
        }
Exemplo n.º 4
0
        /// <inheritdoc/>
        public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
        {
            var configBuilder = builder.ConfigurationBuilder;

            var configFolder = Directory.GetParent(Assembly.GetExecutingAssembly().Location).Parent?.FullName;

            _ = configBuilder.SetBasePath(configFolder);
            _ = configBuilder.AddJsonFile("functionSettings.json");
            _ = configBuilder.AddEnvironmentVariables();

            var configuration = configBuilder.Build();

            AzureKeyVaultConfigurationOptions azureKeyVaultConfigurationOptions = new AzureKeyVaultConfigurationOptions(configuration[ConfigConstants.KeyVaultUrlConfigKey])
            {
                ReloadInterval = TimeSpan.FromSeconds(double.Parse(configuration[Constants.KeyVaultConfigRefreshDurationSeconds])),
            };

            _             = configBuilder.AddAzureKeyVault(azureKeyVaultConfigurationOptions);
            configuration = configBuilder.Build();
            IConfigurationRefresher configurationRefresher = null;

            _ = configBuilder.AddAzureAppConfiguration((options) =>
            {
                _ = options.Connect(configuration[ConfigConstants.AzureAppConfigConnectionstringConfigKey]);
                _ = options.ConfigureRefresh(refreshOptions =>
                {
                    _ = refreshOptions.Register(ConfigConstants.ForceRefreshConfigKey, "Common", refreshAll: true);
                })
                    .Select(KeyFilter.Any, "Common").Select(KeyFilter.Any, "QueueProcessor");
                configurationRefresher = options.GetRefresher();
            });
        }
Exemplo n.º 5
0
 /// <summary>
 /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from the Azure KeyVault.
 /// </summary>
 /// <param name="configurationBuilder">The <see cref="IConfigurationBuilder"/> to add to.</param>
 /// <param name="vaultUri">Azure Key Vault uri.</param>
 /// <param name="credential">The credential to to use for authentication.</param>
 /// <param name="options">The <see cref="AzureKeyVaultConfigurationOptions"/> to use.</param>
 /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
 public static IConfigurationBuilder AddAzureKeyVault(
     this IConfigurationBuilder configurationBuilder,
     Uri vaultUri,
     TokenCredential credential,
     AzureKeyVaultConfigurationOptions options)
 {
     return(configurationBuilder.AddAzureKeyVault(new SecretClient(vaultUri, credential), options));
 }
 /// <summary>
 /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from the Azure KeyVault.
 /// </summary>
 /// <param name="configurationBuilder">The <see cref="IConfigurationBuilder"/> to add to.</param>
 /// <param name="client">The <see cref="SecretClient"/> to use for retrieving values.</param>
 /// <param name="options">The <see cref="AzureKeyVaultConfigurationOptions"/> to use.</param>
 /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
 public static IConfigurationBuilder AddAzureKeyVault(
     this IConfigurationBuilder configurationBuilder,
     SecretClient client,
     AzureKeyVaultConfigurationOptions options)
 {
     options.Client = client;
     return(configurationBuilder.AddAzureKeyVault(options));
 }
Exemplo n.º 7
0
        /// <summary>
        /// Add Key Vault
        ///
        /// You must have a secrets.json defined!
        ///
        /// Some Helpful Links:
        ///		Creating Key Vault in Azure - https://docs.microsoft.com/en-us/azure/key-vault/general/developers-guide
        ///		Key Vault Best Practices - https://docs.microsoft.com/en-us/azure/key-vault/general/best-practices
        ///		Key Vault Access Management - https://docs.microsoft.com/en-us/azure/key-vault/general/overview-security#identity-and-access-management
        ///		Assign a Key Vault Access Policy - https://docs.microsoft.com/en-us/azure/key-vault/general/assign-access-policy-cli
        ///		Using DefaultAzureCredentialOptions - https://www.rahulpnath.com/blog/defaultazurecredential_from_azure_sdk/?utm_source=site-bookmark
        /// </summary>
        /// <param name="debug">Check if debug for local settings vs. production</param>
        /// <param name="builder">The configuration builder object</param>
        /// <param name="initialConfig">The initial config that holds the app config objects</param>
        private static void AddAzureKeyVault(bool debug, ConfigurationBuilder builder, IConfigurationRoot initialConfig)
        {
            // You can call these variables anything you like, this is just what I defaulted them to
            // Please note that when you define a key in Azure Key Vault it should be done with the following structure
            // Example: AppConfig:Database:ConnectionString
            // If you structure it like so it will automatically map to the AppConfig.cs object.  For this example it would map to AppConfig.Database.ConnectionString.
            try
            {
                var akvUri = initialConfig["AzureKeyVaultUri"] ?? throw new ArgumentNullException("AzureKeyVaultUri");
                if (debug)
                {
                    // There are two different ways to connect into this in development mode.
                    // The first is through the AppID and AppSecret of the App Registration that you created to handle your key vault access
                    var appId     = initialConfig["AppId"] ?? throw new ArgumentNullException("AppId");
                    var appSecret = initialConfig["AppSecret"] ?? throw new ArgumentNullException("AppSecret");
                    builder.AddAzureKeyVault(akvUri, appId, appSecret);

                    // The other way to do it is through the DefaultAzureCredentials, see **Using DefaultAzureCredentialOptions**
                    // These default credentials SHOULD default to what you have setup in visual studio, but if they do not you can use the SharedTokenCacheUsername option
                    //var azureCredentialOptions = new DefaultAzureCredentialOptions
                    //{
                    //	SharedTokenCacheUsername = "******"
                    //};
                    //var credentials = new DefaultAzureCredential(azureCredentialOptions);

                    //var azureKeyVaultConfigOptions = new AzureKeyVaultConfigurationOptions()
                    //{
                    //	Vault = akvUri,
                    //	Client = new KeyVaultClient(async (authority, resource, scope) =>
                    //	{
                    //		var token = await credentials.GetTokenAsync(new Azure.Core.TokenRequestContext(new[] { "https://vault.azure.net/.default" }));
                    //		return token.Token;
                    //	}),
                    //	Manager = new DefaultKeyVaultSecretManager()
                    //};
                    //builder.AddAzureKeyVault(azureKeyVaultConfigOptions);
                }
                else
                {
                    // This assumes you have setup a service principle to access the key vault on behalf of this app, see **Assign a Key Vault Access Policy** above
                    var azureKeyVaultConfigOptions = new AzureKeyVaultConfigurationOptions()
                    {
                        Vault   = akvUri,
                        Client  = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(new AzureServiceTokenProvider().KeyVaultTokenCallback)),
                        Manager = new DefaultKeyVaultSecretManager()
                    };

                    builder.AddAzureKeyVault(azureKeyVaultConfigOptions);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from the Azure KeyVault.
        /// </summary>
        /// <param name="configurationBuilder">The <see cref="IConfigurationBuilder"/> to add to.</param>
        /// <param name="client">The <see cref="SecretClient"/> to use for retrieving values.</param>
        /// <param name="options">The <see cref="AzureKeyVaultConfigurationOptions"/> to use.</param>
        /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
        public static IConfigurationBuilder AddAzureKeyVault(
            this IConfigurationBuilder configurationBuilder,
            SecretClient client,
            AzureKeyVaultConfigurationOptions options)
        {
            Argument.AssertNotNull(configurationBuilder, nameof(configurationBuilder));
            Argument.AssertNotNull(options, nameof(configurationBuilder));
            Argument.AssertNotNull(client, nameof(client));
            Argument.AssertNotNull(options.Manager, $"{nameof(options)}.{nameof(options.Manager)}");

            configurationBuilder.Add(new AzureKeyVaultConfigurationSource(client, options));

            return(configurationBuilder);
        }
        public static IHostBuilder AddAzureKeyVaultProvider(this IHostBuilder builder)
        {
            builder.ConfigureAppConfiguration((context, config) =>
            {
                var builtConfig = config.Build();
                var section     = builtConfig.GetSection("AzureKeyVault");

                if (section.Exists())
                {
                    var options = new AzureKeyVaultConfigurationOptions(
                        section["vault"],
                        section["clientId"],
                        section["clientSecret"]);

                    config.AddAzureKeyVault(options);
                }
            });

            return(builder);
        }
Exemplo n.º 10
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.ConfigureAppConfiguration((builderContext, configBuilder) => {
                var configRoot    = configBuilder.Build();
                var isDevelopment = builderContext.HostingEnvironment.IsDevelopment();
                //configBuilder.AddAzureAppConfiguration(configRoot["ConnectionStrings:AppConfig"]);
                configBuilder.AddAzureAppConfiguration(options =>
                {
                    //options.Connect(new Uri(configRoot["ConnectionStrings:AppConfig"]), new DefaultAzureCredential())
                    //    .ConfigureKeyVault(kv =>
                    //    {
                    //        kv.SetCredential(new DefaultAzureCredential());
                    //    });

                    //var defaultAzureCredentialOptions = new DefaultAzureCredentialOptions();


                    //defaultAzureCredentialOptions.ExcludeEnvironmentCredential = true;
                    // defaultAzureCredentialOptions.ExcludeManagedIdentityCredential = true;
                    // defaultAzureCredentialOptions.SharedTokenCacheTenantId = "f5dfe06f-ce39-486a-9341-534321ac9eed";// "f1e27560 -725a-4134-a985-0a66fe1b80ab";
                    // defaultAzureCredentialOptions.SharedTokenCacheUsername = @"live.com#[email protected]";
                    //defaultAzureCredentialOptions.SharedTokenCacheUsername = "******";

                    options.Connect(new Uri(configRoot["ConnectionStrings:AppConfig"]),
                                    isDevelopment ? new DefaultAzureCredential() : (TokenCredential) new ManagedIdentityCredential())
                    .ConfigureKeyVault(kvOptions =>
                    {
                        kvOptions.SetCredential(isDevelopment ? new DefaultAzureCredential() : (TokenCredential) new ManagedIdentityCredential());
                    });
                });
                var kvOptions = new AzureKeyVaultConfigurationOptions(configRoot["ConnectionStrings:KeyVaultConfig"])
                {
                    ReloadInterval = new TimeSpan(0, 15, 0)
                };
                configBuilder.AddAzureKeyVault(kvOptions);
            });

            webBuilder.UseStartup <Startup>();
        });
Exemplo n.º 11
0
 public AzureKeyVaultConfigurationSource(AzureKeyVaultConfigurationOptions options)
 {
     _options = options;
 }
        /// <summary>
        /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from the Azure KeyVault.
        /// </summary>
        /// <param name="configurationBuilder">The <see cref="IConfigurationBuilder"/> to add to.</param>
        /// <param name="options">The <see cref="AzureKeyVaultConfigurationOptions"/> to use.</param>
        /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
        public static IConfigurationBuilder AddAzureKeyVault(this IConfigurationBuilder configurationBuilder, AzureKeyVaultConfigurationOptions options)
        {
            if (configurationBuilder == null)
            {
                throw new ArgumentNullException(nameof(configurationBuilder));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (options.Client == null)
            {
                throw new ArgumentNullException(nameof(options.Client));
            }
            if (options.Vault == null)
            {
                throw new ArgumentNullException(nameof(options.Vault));
            }
            if (options.Manager == null)
            {
                throw new ArgumentNullException(nameof(options.Manager));
            }

            configurationBuilder.Add(new AzureKeyVaultConfigurationSource(options));

            return(configurationBuilder);
        }
Exemplo n.º 13
0
        /// <inheritdoc/>
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var azureFuncConfig = builder?.Services?.BuildServiceProvider()?.GetService <IConfiguration>();
            var configBuilder   = new ConfigurationBuilder();

            _ = configBuilder.AddConfiguration(azureFuncConfig);
            var configFolder = Directory.GetParent(Assembly.GetExecutingAssembly().Location).Parent?.FullName;

            _ = configBuilder.SetBasePath(configFolder);
            _ = configBuilder.AddJsonFile("functionSettings.json");
            _ = configBuilder.AddEnvironmentVariables();

            var configuration = configBuilder.Build();

            MaxDequeueCount = configuration.GetSection(ConfigConstants.MaxDequeueCountConfigKey);

            AzureKeyVaultConfigurationOptions azureKeyVaultConfigurationOptions = new AzureKeyVaultConfigurationOptions(configuration[ConfigConstants.KeyVaultUrlConfigKey])
            {
                ReloadInterval = TimeSpan.FromSeconds(double.Parse(configuration[Constants.KeyVaultConfigRefreshDurationSeconds])),
            };

            _             = configBuilder.AddAzureKeyVault(azureKeyVaultConfigurationOptions);
            configuration = configBuilder.Build();
            _             = configBuilder.AddAzureAppConfiguration(options =>
            {
                var settings = options.Connect(configuration[ConfigConstants.AzureAppConfigConnectionstringConfigKey])
                               .Select(KeyFilter.Any, "Common").Select(KeyFilter.Any, "QueueProcessor");
                _ = settings.ConfigureRefresh(refreshOptions =>
                {
                    _ = refreshOptions.Register(key: configuration[ConfigConstants.ForceRefreshConfigKey], refreshAll: true, label: LabelFilter.Null);
                });
            });

            configuration = configBuilder.Build();

            ITelemetryInitializer[] itm = new ITelemetryInitializer[1];
            var envInitializer          = new EnvironmentInitializer
            {
                Service         = configuration[AIConstants.ServiceConfigName],
                ServiceLine     = configuration[AIConstants.ServiceLineConfigName],
                ServiceOffering = configuration[AIConstants.ServiceOfferingConfigName],
                ComponentId     = configuration[AIConstants.ComponentIdConfigName],
                ComponentName   = configuration[AIConstants.ComponentNameConfigName],
                EnvironmentName = configuration[AIConstants.EnvironmentName],
                IctoId          = "IctoId",
            };

            itm[0] = envInitializer;
            LoggingConfiguration loggingConfiguration = new LoggingConfiguration
            {
                IsTraceEnabled  = true,
                TraceLevel      = (SeverityLevel)Enum.Parse(typeof(SeverityLevel), configuration[ConfigConstants.AITraceLelelConfigKey]),
                EnvironmentName = configuration[AIConstants.EnvironmentName],
            };

            var tconfig = TelemetryConfiguration.CreateDefault();

            tconfig.InstrumentationKey = configuration[ConfigConstants.AIInsrumentationConfigKey];

            DependencyTrackingTelemetryModule depModule = new DependencyTrackingTelemetryModule();

            depModule.Initialize(tconfig);

            RequestTrackingTelemetryModule requestTrackingTelemetryModule = new RequestTrackingTelemetryModule();

            requestTrackingTelemetryModule.Initialize(tconfig);

            _ = builder.Services.AddSingleton <ILogger>(_ => new AILogger(loggingConfiguration, tconfig, itm));

            StorageType storageType = (StorageType)Enum.Parse(typeof(StorageType), configuration?[ConfigConstants.StorageType]);

            if (storageType == StorageType.DocumentDB)
            {
                _ = builder.Services.Configure <CosmosDBSetting>(configuration.GetSection(ConfigConstants.CosmosDBConfigSectionKey));
                _ = builder.Services.Configure <CosmosDBSetting>(s => s.Key = configuration[ConfigConstants.CosmosDBKeyConfigKey]);
                _ = builder.Services.Configure <CosmosDBSetting>(s => s.Uri = configuration[ConfigConstants.CosmosDBURIConfigKey]);
                _ = builder.Services.AddScoped <ICosmosLinqQuery, CustomCosmosLinqQuery>();
                _ = builder.Services.AddSingleton <ICosmosDBQueryClient, CosmosDBQueryClient>();
            }

            _ = builder.Services.Configure <StorageAccountSetting>(configuration.GetSection(ConfigConstants.StorageAccountConfigSectionKey));
            _ = builder.Services.Configure <StorageAccountSetting>(s => s.ConnectionString = configuration[ConfigConstants.StorageAccountConnectionStringConfigKey]);
            _ = builder.Services.AddSingleton <IConfiguration>(configuration);
            _ = builder.Services.AddScoped <IRepositoryFactory, RepositoryFactory>();
            _ = builder.Services.AddScoped <EmailNotificationRepository>();
            _ = builder.Services.AddScoped <IEmailNotificationRepository, EmailNotificationRepository>(s => s.GetService <EmailNotificationRepository>());
            _ = builder.Services.AddScoped <TableStorageEmailRepository>();
            _ = builder.Services.AddScoped <IEmailNotificationRepository, TableStorageEmailRepository>(s => s.GetService <TableStorageEmailRepository>());
            _ = builder.Services.AddScoped <ITableStorageClient, TableStorageClient>();
            _ = builder.Services.AddHttpClient <IHttpClientHelper, HttpClientHelper>();
        }