使用Package Manager控制台将实体框架连接到Key Vault

时间:2019-08-07 15:57:16

标签: entity-framework azure asp.net-core .net-core azure-keyvault

我将我的appSettings.config更改为不再具有连接字符串,因为它们现在都在Azure Key Vault中。我能够毫无问题地进行连接,但是现在当我尝试使用EF代码创建数据库时,首先使用以下命令在新的Azure数据库中进行迁移:

  

添加迁移InitialCreate

我遇到了错误:

Value cannot be null.
Parameter name: connectionString

Startup.cs

   public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add functionality to inject IOptions<T>
        services.AddOptions();

        // Other configurations here such as for Blob and Notification hub
        //
        //

        services.AddDbContext<ObContext>(opt =>
            opt.UseSqlServer(Configuration["obdbqauser"]));

我的Program.cs看起来像这样

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context, config) =>
            {
                //TODO: Seperatre dev and pro - if (context.HostingEnvironment.IsProduction())
                var buildConfig = config.Build();
            //Create Managed Service Identity token provider
            var tokenProvider = new AzureServiceTokenProvider();

            //Create the Key Vault client
            var keyVaultClient = new KeyVaultClient(
                new KeyVaultClient.AuthenticationCallback(
                    tokenProvider.KeyVaultTokenCallback));

            config.AddAzureKeyVault(
                $"https://{buildConfig["VaultName"]}.vault.azure.net/",
                keyVaultClient,
                new DefaultKeyVaultSecretManager());
        })

1 个答案:

答案 0 :(得分:0)

以下是有关如何将Key Vault配置为ASP.NET Core 2.x中的配置源的示例:

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureAppConfiguration((ctx, builder) =>
        {
            //Build the config from sources we have
            var config = builder.Build();
            //Add Key Vault to configuration pipeline
            builder.AddAzureKeyVault(config["KeyVault:BaseUrl"]);
        })
        .Build();

,配置如下:

services.AddDbContext<dbContext>(async options => 
        {
            var keyVaultUri = new Uri("https://xxxxxxxxx.vault.azure.net/");
            var azureServiceTokenProvider = new AzureServiceTokenProvider();
            var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
            SecretBundle connectionStringSecret = await keyVaultClient.GetSecretAsync(keyVaultUri + "secrets/DBConnectionString");
            options.UseSqlServer(connectionStringSecret.Value);
        });

您需要Microsoft.Extensions.Configuration.AzureKeyVault才能获取Key Vault的配置提供程序。

Key Vault中的秘密命名很重要。例如,我们将覆盖以下连接字符串:

{
  "ConnectionStrings": {
    "DefaultConnection": "..."
  }
}

您将必须创建一个名为ConnectionStrings--DefaultConnection的秘密,并以连接字符串作为值。

然后在配置时,只需使用Configuration [“ ConnectionStrings:DefaultConnection”]即可获取连接字符串。如果添加了Key Vault配置并找到了具有正确名称的机密,它将来自Key Vault。

作为参考,请查看此link

https://entityframeworkcore.com/knowledge-base/53103236/azure-keyvault-for-dbcontext---no-database-provider-has-been-configured-for-this-dbcontext-

希望有帮助。