H. Pauwelyn
H. Pauwelyn

Reputation: 14320

Use Key vault to store default connection string of ABP Framework

We've uploaded my ABP Framework site to an Azure Web application but the default connection string is stored inside the configuration of the web app. Now we want to replace that to an Azure Key Vault and store only the URL inside the configuration.

Where using this code:

using Azure.Extensions.AspNetCore.Configuration.Secrets;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Extensions.Configuration;
using System;

namespace OurNamespace.Utils
{
    public static class AppAzureKeyVaultConfigurer
    {
        public static IConfigurationBuilder ConfigureAzureKeyVault(this IConfigurationBuilder builder, string azureKeyVaultUrl)
        {
            SecretClient keyVaultClient = new SecretClient(
                new Uri(azureKeyVaultUrl),
                new DefaultAzureCredential()
            );

            AzureKeyVaultConfigurationOptions options = new AzureKeyVaultConfigurationOptions()
            {
                ReloadInterval = TimeSpan.FromHours(1)
            };

            return builder.AddAzureKeyVault(keyVaultClient, options);
        }
    }
}

Inside the Program class of the OurNamespace.HttpApi.Host project, next code will be called:

internal static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .AddAppSettingsSecretsJson()
        .ConfigureAppConfiguration(build =>
        {
            IConfigurationBuilder configuration = build
                .AddJsonFile("appsettings.secrets.json", optional: true)
                .ConfigureAzureKeyVault("☺ --> the url to the key vault");
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        })
        .UseAutofac()
        .UseSerilog();

To get the assess token inside the OurApplicationDbContext:

[ReplaceDbContext(typeof(IIdentityProDbContext), typeof(ISaasDbContext), typeof(ILanguageManagementDbContext), typeof(IAuditLoggingDbContext), typeof(ITextTemplateManagementDbContext), typeof(IIdentityServerDbContext), typeof(IPaymentDbContext), typeof(IPermissionManagementDbContext), typeof(ISettingManagementDbContext), typeof(IFeatureManagementDbContext), typeof(IBackgroundJobsDbContext), typeof(IBlobStoringDbContext))]
[ConnectionStringName("Default")]
public class OurApplicationDbContext : AbpDbContext<OurApplicationDbContext>, IOurApplicationDbContext, IIdentityProDbContext, ISaasDbContext, ILanguageManagementDbContext, IAuditLoggingDbContext, ITextTemplateManagementDbContext, IIdentityServerDbContext, IPaymentDbContext, IPermissionManagementDbContext, ISettingManagementDbContext, IFeatureManagementDbContext, IBackgroundJobsDbContext, IBlobStoringDbContext
{
    private readonly IConfiguration _configuration;

    // All implementations of all interfaces here

    public OurApplicationDbContext(DbContextOptions<OurApplicationDbContext> options, IConfiguration configuration)
        : base(options)
    {
        _configuration = configuration;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured) // <-- also a break point here will not be hit.
            optionsBuilder.UseSqlServer(_configuration.GetConnectionString("Default"));
    }
}

Inside the appsettings.json the Connectionstring:Default is removed because it must be taken from the Key Vault.

Also in the DbContext of the OurNamespace.EntityFrameworkCore project, all these DbContexts are replaced:

It will give next error:

ArgumentNullException: Value cannot be null. (Parameter connectionString)

DependencyResolutionException: An exception was thrown while activating: Volo.Abp.LanguageManagement.EntityFrameworkCore.ILanguageManagementDbContextOurNamespace.EntityFrameworkCore.OurApplicationDbContextMicrosoft.EntityFrameworkCore.DbContextOptions<OurNamespace.EntityFrameworkCore.OurApplicationDbContext>.

Update

If I do nothing (placing my connection string key inside the appsettings.json file), the ILanguageManagementDbContext will work as expected. Also other keys from the Key Vault will be taken. Also checked that the correct key is stores inside Key Vault and didn't find any problems.

Specifications

Upvotes: 2

Views: 2031

Answers (1)

Tiny Wang
Tiny Wang

Reputation: 16066

Follow this document, it showed when we want to add azure keyvault secrets into configuration, we can use managed identities for getting azure resources. That is what OP used DefaultAzureCredential. Using DefaultAzureCredential required to do some configuration to make sure we've provided credential for our application. For local test, we used visual studio, so we can use the account which has azure key vault access permission to sign in visual studio, this can be one of the credential. And if we've published the application to azure app service, then also add the web app service princple to the key vault access policy.

enter image description here

Here's my sample code.

My program.cs, add ConfigureAppConfiguration:

using Azure.Extensions.AspNetCore.Configuration.Secrets;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;

namespace WebMvcAppLinkDb
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((context, config) =>
                {
                    var builtConfig = config.Build();
                    var secretClient = new SecretClient(
                        new Uri($"https://{builtConfig["KeyVaultName"]}.vault.azure.net/"),
                        new DefaultAzureCredential());
                    config.AddAzureKeyVault(secretClient, new KeyVaultSecretManager());
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

My startup.cs,

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    //use connection string stored in appsetting
    //services.AddDbContext<MyDbContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("MvcMovieContext")));
    //use connection string stored in azure key vault
    //after adding Azure Key Vault configuration provider, we debug code here, and will see Cigfiguration has one more provider from keyvault
    var a = Configuration.GetSection("LocalDbConnectionString");
    var b = a.Value;
    var c = b.ToString();
    //I stored connection string with name "LocalDbConnectionString" in azure keyvault, but when I get the value from key vault
    //I don't know why the data format like Server=(localdb)\\\\xxdb, so I need to remove \\
    var d = c.Remove(16,1);
    services.AddDbContext<MyDbContext>(options =>options.UseSqlServer(d));
}

My appsetting:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  //"ConnectionStrings": {
  //  "MvcMovieContext": "Server=(localdb)\\xxdb;Database=xx;Trusted_Connection=True;MultipleActiveResultSets=true"
  //},
  "KeyVaultName": "my_keyvault_name"
}

Upvotes: 1

Related Questions