Persist Asp.NET Core Identity Cookies to Database

If you've ever had an issue where your cookie auth isn't persisted; i.e. users keep getting logged out after about 15 minutes in prod, then this is the fix for you.

Start by installing the NuGet package: Microsoft.AspNetCore.DataProtection.EntityFrameworkCore

Then implement the IDataProtectionKeyContext in your DbContext class like so:

public class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : IdentityDbContext(options), IDataProtectionKeyContext
{
    // … Your other stuff
    public DbSet<DataProtectionKey> DataProtectionKeys { get; set; }
}

Then configure the data protection service in your DI container

        // Configure Data Protection
       services.AddDataProtection()
           .PersistKeysToDbContext<ApplicationDbContext>()
           .SetApplicationName("YourAppName");

Generate migrations and update your database

Voila!