【问题标题】:Safely create new instance of EF Core DbContext安全地创建 EF Core DbContext 的新实例
【发布时间】:2021-02-28 02:52:04
【问题描述】:

有时在 .NET Core 中存在需要多个 DbContext 的情况(并行数据库请求等)。

在我的 DbContext 类中使用这两种解决方案中的任何一种是否安全?

    private static string _connectionString;

    private static string ConnectionString => 
        _connectionString ??= new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build().GetConnectionString("CoreConnection");

    public static CoreContext GetContext()
    {
        var options = new DbContextOptionsBuilder<CoreContext>()
            .UseNpgsql(ConnectionString)
            .Options;

        return new CoreContext(options);
    }

    private static IConfiguration _configuration;

    private static IConfiguration Configuration =>
        _configuration ??= new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();

    private static string ConnectionString => 
        Configuration.GetConnectionString("CoreConnection");

    public static CoreContext GetContext()
    {
        var options = new DbContextOptionsBuilder<CoreContext>()
            .UseNpgsql(ConnectionString)
            .Options;

        return new CoreContext(options);
    }

我已经阅读(对于旧的 ASP .NET),您应该避免将敏感数据(例如密码和包含密码的连接字符串)以纯文本形式保存在应用程序内存中,因为内存可能在崩溃后被黑客入侵或转储/保存。

.NET Core 仍然如此吗? (应该是这样)

使用IConfiguration 是否更安全,或者它是否也将连接字符串以纯文本形式存储在内存中?

net core中可与DI一起使用的全局IConfiguration是否将所有appsettings.json文件数据存储在内存中?

内存被黑客入侵的可能性更大,那么黑客可能能够直接读取appsettings.json 信息吗?

【问题讨论】:

    标签: c# security .net-core entity-framework-core


    【解决方案1】:

    我认为这可能会有所帮助。

    使用后处理 DbContext 非常重要。这确保 任何非托管资源都被释放,任何事件或 其他钩子未注册,以防止内存泄漏,以防万一 实例仍然被引用。 DbContext 不是线程安全的。不要 在线程之间共享上下文。确保等待所有异步调用 在继续使用上下文实例之前。一个 EF Core 代码抛出的 InvalidOperationException 可以放置上下文 进入不可恢复的状态。此类异常表示程序错误 并且不是为了恢复而设计的。

    https://docs.microsoft.com/en-us/ef/core/dbcontext-configuration/

    这也有帮助:

    切勿在源代码中存储密码或其他敏感数据。

    https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-5.0&tabs=windows

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-20
      • 2018-11-02
      • 1970-01-01
      • 1970-01-01
      • 2019-02-10
      • 1970-01-01
      • 2018-04-19
      • 2021-01-02
      相关资源
      最近更新 更多