【问题标题】:Replacing AppSettings with KeyVault values - timing question用 KeyVault 值替换 AppSettings - 时间问题
【发布时间】:2022-11-03 18:30:56
【问题描述】:

我正在编写一个 .NET Core 6 Web API 并尝试转换为使用密钥保管库。我在CreateAppConfiguration 部分调用AddAzureKeyVault 但我需要在Startup.cs 的ConfigureServices 方法中调整数据库连接字符串,因为这是我们设置服务(包括SQL Server)的地方。即使当我停在ConfigurationServices 内时,我已经超过了AddAzureKeyVault 中的断点,但我看到了appsettings 文件中的原始虚拟值。后来,在我的控制器方法中,它们很好地覆盖在我的appsettings 之上,正如您所期望的那样。

目前,我在那里加载 keyvault 值只是为了使其工作,但必须有一些更好的方法以便更快地加载 keyvault 值 - 有吗?我还能把它放在哪里?

来自 Program.cs

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
               .ConfigureAppConfiguration(config =>
               {
                   ...
                   config.AddAzureKeyVault(new Uri(vaultUrl), credential, new PrefixKeyVaultSecretManager("KVTest"));
               })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

来自 Startup.cs

     public void ConfigureServices(IServiceCollection services)
        {
            //======================= new key vault stuff ===========================
            // The key vault values have NOT been applied yet, so we need to manually grab the DB conn string here
            var connString = Configuration.GetConnectionString("InformCoreDbContext");
            //^^ I see the dummy string from the appsettings file here

            //======================= horrible kludge ===============================
            // If I open the keyvault and grab the conn string that works, but
            // I shouldn't have to do this here since I'm overloading them at some point
            connString = temporaryMachinationsToGrabKeyVaultConnString();
                    
            services.AddPooledDbContextFactory<ICAdminContext>(options =>
              options.UseSqlServer(connString,
              sqlServerOptionsAction: sqlOptions =>
              {
                  sqlOptions.EnableRetryOnFailure();
              }));

注意:我确实阅读了how-to-get-azure-keyvault-key-inside-config,但该解决方案对我不起作用。扩展方法中的配置对象仍然没有加载 keyvault 条目。

【问题讨论】:

    标签: sql-server .net-core azure-keyvault


    【解决方案1】:

    检查以下解决方法以使用 Azure Key Vault 覆盖应用程序设置的值。 感谢@Wouter 的解释。

    • 最初创建 .NET 6 Web API 并发布到 Azure。

    我的 appsettings.json

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "managedinstance": "Wonderland",
      "KeyVaultName": "harshithakeyvault",
      "Secrets": {
        "One": "@Microsoft.KeyVault(Secreturi=[uri to secret copied from Azure blade])"
      },
      "AllowedHosts": "*"
    }
    
    

    来自本地的初始应用程序设置值

    • 创建托管标识,命名与部署的Azure App Service 名称相同。

    • 在 Azure 门户中,创建 KeyVault,授予对密钥保管库的访问权限。

    • 创建Access policy => 选择Get,List 权限=> 搜索principalThe principal name will be same as the App service name=> Review + create

    • 在 Azure Key Vault 中创建新机密, Secrets => Generate/Import。

    • 在部署的Azure App中,确保系统Identity状态为on。
    • 在 Azure 应用设置中,在 Azure KeyVault 中添加名称与 Secret 相同的密钥。

    复制 KeyVault 机密中的 Secret Identifier。

    将 KeyVault 机密中的 uri 替换为 Secret Identifier。

    我的程序.cs

    using Azure.Identity;
    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddControllers();
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    
    var app = builder.Build();
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }
    builder.Configuration.AddAzureKeyVault(
          new Uri($"https://{builder.Configuration["KeyVaultName"]}.vault.azure.net/"),
          new DefaultAzureCredential());
    app.UseHttpsRedirection();
    app.UseAuthorization();
    app.MapControllers();
    app.Run();
    

    在控制器中

     private readonly IConfiguration Configuration;
     public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
            {
                _logger = logger;
                Configuration = configuration;
            }
            
     [HttpGet(Name = "GetWeatherForecast")]
     public IEnumerable<WeatherForecast> Get()
     {
         return Enumerable.Range(1, 5).Select(index => new WeatherForecast
         {
             Date = DateTime.Now.AddDays(index),
             TemperatureC = Random.Shared.Next(-20, 55),
             Summary = Summaries[Random.Shared.Next(Summaries.Length)],
    
             Myvalues = Configuration.GetSection("managedinstance").Value
         })
         .ToArray();
     }
    

    .csproj 文件

    <Project Sdk="Microsoft.NET.Sdk.Web">
      <PropertyGroup>
        <TargetFramework>net6.0</TargetFramework>
        <Nullable>enable</Nullable>
        <ImplicitUsings>enable</ImplicitUsings>
      </PropertyGroup>
    
      <ItemGroup>
        <PackageReference Include="Azure.Extensions.AspNetCore.Configuration.Secrets" Version="1.2.2" />
        <PackageReference Include="Azure.Identity" Version="1.7.0" />
        <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
      </ItemGroup>
    </Project>
    

    最终输出 - 来自 KeyVault 的值

    参考来自Link

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 2023-02-15
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多