.NET Core 6:保护连接字符串中潜在的敏感信息

Joe*_*ack 3 .net c# asp.net-core-mvc asp.net-core-6.0

如何将下面的敏感信息移至“秘密管理工具”中?

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlServer("Server=Test; column encryption setting=enabled;Database=Test;user id=User1;password='Password1';Trust Server Certificate=true");
Run Code Online (Sandbox Code Playgroud)

我知道我可以右键单击解决方案名称并选择“管理用户机密”,然后生成机密 Json 文件,但我要粘贴到此文件中的内容是什么?

当我将此应用程序移至生产服务器时,我是否secret.json也复制并粘贴?

提前致谢。

Gur*_*ron 5

您需要退一步考虑 ASP.NET Core/.NET 提供的用于配置的工具。

DbContext 生命周期、配置和初始化文档中,您可以看到常见模式之一是使用依赖项注入并在应用程序启动时设置连接字符串。这将需要向上下文添加构造函数(并修改/删除OnConfiguring重载 -文档):

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

和:

builder.Services.AddDbContext<ApplicationDbContext>(
        options => options.UseSqlServer("ConnectionStringHere")); // or AddDbContextFactory
Run Code Online (Sandbox Code Playgroud)

下一步是从设置中读取连接字符串:

builder.Services.AddDbContext<ApplicationDbContext>(
        options => options.UseSqlServer(builder.Configuration.GetConnectionString("ConnStringName"))); // or AddDbContextFactory
Run Code Online (Sandbox Code Playgroud)

这将需要从配置中读取连接字符串,例如从 appsettting.json 中读取:

builder.Services.AddDbContext<ApplicationDbContext>(
        options => options.UseSqlServer("ConnectionStringHere")); // or AddDbContextFactory
Run Code Online (Sandbox Code Playgroud)

您还可以将连接字符串移动到任何受支持的配置提供程序,例如 - Secret Manager(注意,它仅适用于开发环境,对于其他环境,最好使用环境变量或安全密钥存储)。