gpt4 book ai didi

c# - 使用KeyVault存储ABP框架的默认连接字符串

转载 作者:行者123 更新时间:2023-12-02 23:55:55 29 4
gpt4 key购买 nike

我们已将我的 ABP 框架站点上传到 Azure Web 应用程序,但默认连接字符串存储在 Web 应用程序的配置中。现在我们想将其替换为 Azure Key Vault,并仅将 URL 存储在配置中。

在哪里使用此代码:

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);
}
}
}

ProgramOurNamespace.HttpApi.Host 的类别项目,接下来的代码将被调用:

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();

获取OurApplicationDbContext内的评估 token :

[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"));
}
}

appsettings.jsonConnectionstring:Default已删除,因为它必须从 Key Vault 中获取。

也在DbContextOurNamespace.EntityFrameworkCore的项目,所有这些DbContext s 被替换:

  • IIdentityProDbContext
  • ISaasDbContext
  • ILanguageManagementDbContext
  • IAuditLoggingDbContext
  • ITextTemplateManagementDbContext
  • IIdentityServerDbContext
  • IPaymentDbContext
  • IPermissionManagementDbContext
  • ISettingManagementDbContext
  • IFeatureManagementDbContext
  • IBackgroundJobsDbContext
  • IBlobStoringDbContext

它将给出下一个错误:

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>.

更新

如果我什么都不做(将我的连接字符串 key 放入 appsettings.json 文件中),则 ILanguageManagementDbContext将按预期工作。 Key Vault 中的其他 key 也将被取走。还检查了 Key Vault 中存储的 key 是​​否正确,没有发现任何问题。

规范

  • ABP框架版本:5.0.0
  • UI 类型:Angular
  • 数据库提供商:EF Core

最佳答案

关注this documen t,它表明当我们想要将 azure keyvault secret 添加到配置中时,我们可以使用托管身份来获取 azure 资源。这就是OP使用的DefaultAzureCredential。使用 do some configuration 所需的 DefaultAzureCredential确保我们已为我们的应用程序提供了凭据。对于本地测试,我们使用的是Visual Studio,因此我们可以使用azure key vault access permission的帐户要登录 Visual Studio,这可以是凭据之一。如果我们已将应用程序发布到 azure 应用服务,那么还要将 Web 应用服务原则添加到 key 保管库访问策略中。

enter image description here

这是我的示例代码。

我的program.cs,添加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>();
});
}
}

我的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));
}

我的应用程序设置:

{
"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"
}

关于c# - 使用KeyVault存储ABP框架的默认连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71853588/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com