[Infra] Persist DataProtection keys in the DB (fixes logout/antiforgery on deploy)

Add Microsoft.AspNetCore.DataProtection.EntityFrameworkCore; AppDbContext implements IDataProtectionKeyContext with a DataProtectionKeys set; PersistKeysToDbContext + SetApplicationName(hamkadr). Now the key ring is shared across restarts/replicas, so auth cookies, antiforgery tokens and the captcha no longer break on every deploy (the root cause of the earlier admin lock-out). Migration: DataProtectionKeys table.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
soroush.asadi
2026-06-07 07:33:20 +03:30
parent c46e628f6a
commit 437258294b
6 changed files with 1336 additions and 1 deletions
+8
View File
@@ -3,6 +3,7 @@ using System.Text.Unicode;
using JobsMedical.Web.Data;
using JobsMedical.Web.Models;
using JobsMedical.Web.Services;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Mvc;
@@ -77,6 +78,13 @@ builder.Services.AddSingleton(HtmlEncoder.Create(
builder.Services.AddDbContext<AppDbContext>(opt =>
opt.UseNpgsql(builder.Configuration.GetConnectionString("Default")));
// Persist the DataProtection key ring in the DB so antiforgery tokens, auth cookies and the
// captcha survive deploys/restarts (otherwise a new key ring each boot logs everyone out and
// breaks antiforgery — the cause of the earlier admin lock-out).
builder.Services.AddDataProtection()
.PersistKeysToDbContext<AppDbContext>()
.SetApplicationName("hamkadr");
var app = builder.Build();
// Apply migrations + seed on startup (fine for MVP single-instance deploy).