Search code examples
entity-framework-coreasp.net-core-mvcmediatr

ASP.NET Core MVC. Implementation of the IDataProtectionKeyContext interface


There is a data context:

public class OurDbContext : DbContext, IOurDbContext, IDataProtectionKeyContext
{
    public DbSet<Employee> Employees { get; set; }
    
    public DbSet<Role> Roles { get; set; }
    
    public DbSet<DataProtectionKey> DataProtectionKeys { get; set; } = null!;
}

There is a method that implements sending data to the database:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateNewClient(Employee client, string TypeOfClient)
{
    var secstring = _protector.Protect(client.Password);

    Employee temp = new Employee
    {
        Name = client.Name,
        Password = secstring,
        RoleId = 1
    };
    await _mediatr.Send(new NewEmployee.NewEmployeeCommand(temp));
    return Redirect("~/");
}

Nothing gets into the database.

If you remove the implementation from the context class IDataProtectionKeyContext

public DbSet<DataProtectionKey> DataProtectionKeys { get; set; } = null!;

and shorten the line with

builder.Services.AddDataProtection().PersistKeysToDbContext<OurDbContext>();

before

builder.Services.AddDataProtection();

then the data gets into the database with an encrypted password. But in this case, after 5 minutes, an attempt to read this password will cause an exception due to an outdated key.

The Microsoft help doesn't say anything about this:

https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?view=aspnetcore-6.0#persistkeystodbcontext


Solution

  • In short, I tried to change the context from PostgreSQL to MS SQL and Sqlite, and everything works well in them with the configuration that Microsoft recommends in its help.