A production-grade authentication and authorization backend built with ASP.NET 10 and PostgreSQL. Designed as a reusable starter for SaaS applications that need encrypted user data, tag-based permissions, rotating refresh-token sessions, and a full admin dashboard — out of the box.
Built by Márk Pásztor — This project reflects my approach to backend architecture: security-first, vertically sliced, and ready to extend, proven in personal hobby projects and production.
- Field-Level Encryption — Emails, usernames, and PII are AES-256-GCM encrypted at rest with a versioned key ring, automatic re-encryption on rotation, and blind-index lookups for querying
- Pepper-Versioned Blind Indexes — Searchable encrypted fields using HMAC-SHA256 with rotatable pepper keys
- Rotating Refresh Tokens — Refresh tokens are bound to the User-Agent, rotate on every use, remember the last five hashes, and a replayed token revokes the device session
- Avatar Pipeline — Uploads are decoded with SkiaSharp, resized to 512px, re-encoded as WebP without metadata, and stored in any S3-compatible bucket (MinIO in compose)
- Tag-Based RBAC — Flexible permission system where tags (Member, Pro, Admin, etc.) map to granular feature permissions
- Silent Token Refresh — Middleware transparently refreshes expired JWTs using HTTP-only cookies, no client-side token handling
- Store Auth Mode — Optional deployment mode that replaces email + password with Sign in with Apple and Google Sign-In, verified server-side from the native ID token
- Soft Delete & GDPR Anonymization — Users can deactivate accounts with immediate anonymization, e-mail-confirmed reactivation, and automatic purge after 30 days
- Activity Tracking — Buffered heartbeat system with a background service that batch-writes page-level engagement data
- Comprehensive Rate Limiting — Per-endpoint, per-client (user id or IP) fixed-window rate limiting across 13 policy tiers, Redis-backed when
Redis__ConnectionStringis set - Transactional Email System — Templated HTML emails for confirmation, password recovery, security alerts, and account actions via SMTP/MailKit
auth-template/
├── Configuration/ Global config (rate limits, regexes, device rules)
├── Entities/ DbContext, data models, seed configurations
│ ├── Configuration/ EF seed data & permission mappings
│ ├── Data/ Entity classes (AppUser, AppPermission, etc.)
│ └── Interfaces/ ISoftDeletable, IAnonymizable
├── Enums/ Shared enums
├── Features/ Vertical slices (one folder per domain)
│ ├── Auth/ Registration, login, logout, token management
│ │ ├── Attributes/ [WithPermissions], [OwnerOrPermission]
│ │ ├── Configuration/ Auth constants (token lifetimes, lockout rules)
│ │ ├── Controllers/ AuthController
│ │ ├── Entities/ AppRefreshToken, AppUserPreferences
│ │ ├── Responses/ SelfResponse, PermissionTransfer, etc.
│ │ ├── Services/ AuthService, IAuthService
│ │ ├── Transfer/ DTOs (RegisterDto, LoginDto, etc.)
│ │ ├── Utilities/ JWT, Refresh, Permissions, Activity, User
│ │ └── Validation/ FluentValidation rules
│ ├── Admin/ Dashboard KPIs, user management, audit logs
│ ├── Email/ Confirmation, password reset, email change
│ └── Profile/ User profiles, avatars, visibility toggle
├── Middleware/ TokenRefresh, ErrorHandler
├── Options/ Strongly-typed config (Security, Database, CORS)
├── Responses/ Shared response envelope (Response<T>, Paged<T>)
├── Utilities/ Encryption, hashing, auditing, rate limiting
│ └── Security/ Encryptor, GeneralHasher, PasswordVerifier, PepperProvider
├── Migrations/ EF Core migration history
├── Program.cs Application bootstrap & DI configuration
└── Dockerfile Multi-stage Linux container build
Each Feature follows the same internal structure (Controllers → Services → Utilities → Transfer → Validation → Responses), keeping related code colocated and minimizing cross-feature coupling.
PII columns are encrypted with AES-256-GCM (authenticated, random nonce per value) under a versioned key ring: Email, NormalizedEmail, UserName, NormalizedUserName, DisplayName, AvatarUrl and BanReason on users, Bio, Headline, DateOfBirth and Location on profiles, UserAgent and IpAddress on refresh tokens. Ciphertext carries its key version ($2$…), rows written by older releases with AES-CBC still decrypt with key version 1, and EF Core value converters make all of this transparent to application code.
Key rotation: add Security__Keys__AesKeys__2, set Security__Keys__AesCurrentVersion=2, deploy. New writes use the new key immediately and a background job (ReEncryptionJob, 2 minutes after start and every 12 hours) rewrites older rows in batches of 200. Remove the old key only after the job logs no remaining rows. HMAC and JWT keys rotate without downtime through Security__Keys__PreviousHmacSecretKey and Security__Keys__PreviousJwtSigningKey: both keys are accepted while set, and refresh tokens are re-hashed with the current key on their next use.
Because the key lives only in configuration (Security__Keys__AesKey), database dumps and backups contain ciphertext for every PII column. Keep the key out of the backup set and rotate it independently; anyone holding both a backup and the key can read the data. Deactivation overwrites the PII columns immediately, and the purge job deletes the rows after 30 days, so backups taken after that point contain nothing about the user. Per-user encryption keys would only add crypto-shredding value with a key store that is backed up separately from the database (for example a KMS); this template does not include one.
Since encrypted values can't be queried with WHERE, each encrypted field has a corresponding blind index column — an HMAC-SHA256 hash computed with a versioned pepper. This allows exact-match lookups on encrypted data without exposing the plaintext.
Peppers are versioned (1–7 slots), and the system automatically upgrades old indexes to the current version on read (lazy migration).
| Token | Storage | Lifetime | Protection |
|---|---|---|---|
| JWT Access | HttpOnly + Secure + SameSite=None cookie |
10 min | HMAC-SHA256 signed |
| Refresh | HttpOnly + Secure + SameSite=None cookie |
3 months, sliding | HMAC-SHA256 hashed before storage, bound to the User-Agent hash, rotated on every refresh |
Refresh tokens are never stored in plaintext — only the HMAC hash is persisted. Every refresh issues a new token and remembers the last five hashes of that device. Presenting a rotated token within 30 seconds (parallel requests from one page load) still yields an access token; presenting any remembered older token later is treated as theft and revokes that device session. Password resets, bans and logout revoke refresh tokens.
Tags (roles) Permissions (features)
┌──────────────┐ ┌─────────────────────────┐
│ Member │──┬──▶│ Content.Read │
│ │ ├──▶│ Content.Create │
│ │ ├──▶│ Content.Update │
│ │ └──▶│ Users.Read │
├──────────────┤ ├─────────────────────────┤
│ ProTier │─────▶│ Content.ProFeature │
├──────────────┤ ├─────────────────────────┤
│ Administrator│──┬──▶│ Users.Delete │
│ │ ├──▶│ System.AuditLogs.View │
│ │ ├──▶│ System.Roles.Manage │
│ │ └──▶│ System.Settings.Manage │
└──────────────┘ └─────────────────────────┘
Tags are assigned to users. Each tag maps to a set of permissions via seed data. The [WithPermissions("Permission.Name")] attribute on endpoints checks the user's resolved permissions. Permissions are cached in-memory with a 10-minute TTL.
One deployment runs exactly one authentication mode, selected by Auth:Mode.
| Mode | Registration & sign-in | Endpoints hidden (404) |
|---|---|---|
Password (default) |
Email/username + password | POST /api/auth/store/sign-in |
Store |
Native Apple / Google ID token via POST /api/auth/store/sign-in |
/register, /register/admin, /login, /availability/*, /change/password, /api/email/forgot-password* |
In Store mode the app sends the ID token it received from the platform SDK. The backend validates the signature against the provider's published keys, checks issuer, audience, and expiry, and requires a verified email. New users are provisioned without a password, with EmailConfirmed = true and a generated username they can change later. Returning users are matched by provider + subject in AspNetUserLogins; an email that already belongs to another account is rejected with 409 rather than linked.
Configuration (environment variables shown; appsettings.json uses the equivalent nested keys):
Auth__Mode=Store
Auth__Store__Google__ClientIds__0=<google-oauth-client-id>
Auth__Store__Apple__BundleIds__0=<ios-bundle-id>Startup fails in Store mode when neither list has an entry. Refresh, logout, profile, admin, reactivation and email-change endpoints work identically in both modes. Administrators are created with POST /api/auth/register/admin in Password mode, or by signing in normally and calling POST /api/auth/admin/promote with the Security__AdminPassword secret in either mode.
- .NET 10 SDK
- PostgreSQL (or Docker)
- Mailhog (for local email testing)
git clone https://github.com/pasztor-mark/auth-template.git
cd auth-template
cp .env.example .envOpen .env and fill in your values. Generate keys with:
# AES / JWT / HMAC keys (32-byte, base64)
openssl rand -base64 32
# Blind index peppers (64-byte, hex)
openssl rand -hex 64Option A, everything in Docker (API, PostgreSQL 17, Redis, MinIO, Mailhog):
docker compose up --buildThe API listens on http://localhost:5377, PostgreSQL on localhost:2345, Redis on localhost:6379, MinIO on localhost:9000 (console :9001, bucket avatars created with public read), Mailhog UI on http://localhost:8025. Migrations run on container start (Database__MigrateOnStartup=true is set in compose.yaml).
Option B, only the dependencies in Docker and the API from the SDK:
docker compose up -d db redis minio minio-init mailhog
dotnet run --launch-profile httpsIn Development the API applies pending EF migrations at startup, so no separate dotnet ef database update is needed. https://localhost:5377/health reports database connectivity and https://localhost:5377/openapi/v1.json serves the OpenAPI document (Development only).
All settings come from environment variables (.env in Development, real environment variables elsewhere). Section__Key maps to Section:Key in appsettings.json.
| Key | Purpose |
|---|---|
Security__Keys__AesKey |
32-byte base64 key for AES-256-CBC field encryption |
Security__Keys__JwtSigningKey |
HS256 signing key, at least 32 bytes |
Security__Keys__HmacSecretKey |
Key for hashing refresh tokens, at least 32 bytes |
Security__BlindIndexPeppers__N, Security__CurrentVersion |
Hex peppers for blind indexes and the active version |
Security__IssuerAudiencePair |
issuer;audience for JWTs |
Security__AdminPassword |
Shared secret for POST /api/auth/register/admin; empty disables the endpoint |
Security__SmtpPassword |
SMTP password; empty skips SMTP authentication |
Database__ConnString or Database__Host/Port/Name/User/Password |
PostgreSQL connection |
Database__MigrateOnStartup |
Apply migrations at startup (default: Development only) |
Database__ApiUrl, FrontendUrl |
Base URLs used in e-mail links |
Email__Host/Port/Address/SenderName/SecureSocket |
SMTP endpoint, sender, and TLS mode (Auto, StartTls, SslOnConnect, None) |
Cors__AllowedOrigins |
Comma separated browser origins |
Redis__ConnectionString |
Redis for rate limits and the permission cache; empty keeps them in process (single instance only) |
Storage__ServiceUrl/Bucket/AccessKey/SecretKey/PublicBaseUrl |
S3-compatible avatar storage; empty bucket disables uploads |
Security__Keys__AesKeys__N, Security__Keys__AesCurrentVersion |
AES key ring (version 1 defaults to AesKey) |
Security__Keys__PreviousHmacSecretKey, Security__Keys__PreviousJwtSigningKey |
Overlap keys for zero-downtime rotation |
Auth__Mode, Auth__Store__* |
Password or Store mode and provider audiences |
Network__TrustForwardedHeaders, Network__KnownProxies, Network__KnownNetworks |
Reverse proxy trust for X-Forwarded-For/Proto |
Genai__Gemini__ApiKey, Genai__Gemini__BaseUrl |
Gemini API key and base URL; empty key holds queued requests as Misconfigured instead of dead-lettering them |
Startup fails fast with a descriptive message when a required key is missing or malformed.
All keys live under Notifications (Notifications__Retention__KeepLast as an environment variable). Every value is validated at startup.
| Key | Default | Purpose |
|---|---|---|
Enabled |
true |
Master switch; endpoints answer 501 and QueueAsync is a no-op when off |
Read:DefaultPageSize / Read:MaxPageSize |
20 / 50 |
Page bounds (max 100) |
Read:DefaultActorRef |
Both |
Response shape when ?actor= is absent |
Aggregation:Enabled / Threshold / Window |
true / 3 / 24:00:00 |
Read-time collapsing of rows sharing an aggregate key |
Retention:Enabled |
true |
Off disables the trim service (boot warning) |
Retention:KeepLast / HardCap |
15 / 100 |
Keep the newest N plus unread, never more than the cap |
Retention:MaxAge |
unset | Optional age bound for time-based audit policies |
Retention:FlushInterval / QueueCapacity |
00:00:30 / 10000 |
Trim drain window and bounded queue |
Stream:Enabled |
true |
Off makes /events answer 501; clients poll /badge |
Stream:HeartbeatInterval |
00:00:15 |
: ping cadence (5–60 s; proxies reap past 60) |
Stream:MaxConnectionsPerUser / MaxConnections |
3 / 5000 |
Socket caps → 429 / 503 |
Stream:ClientBufferSize |
64 |
Per-connection buffer before a laggard is disconnected |
Stream:ReplayLimit |
200 |
Last-Event-ID rows before event: resync |
Stream:ChannelPrefix |
notif: |
Redis pub/sub prefix |
Preferences:Enabled |
true |
Off makes the preference endpoints answer 501 |
Preferences:DefaultInApp / DefaultPush |
true / true |
Meaning of an absent preference row |
Preferences:QuietHoursEnabled |
true |
Off ignores quiet-hour fields on write |
All keys live under Genai (Genai__Gemini__ApiKey as an environment variable). Provider-agnostic gateway for generative-model calls — see docs/superpowers/specs/2026-09-10-genai-adapter-design.md for the full design.
| Key | Default | Purpose |
|---|---|---|
Gemini:ApiKey |
"" |
Empty holds every queued request as Misconfigured without burning retry attempts; sync calls fail the same way |
Gemini:BaseUrl |
https://generativelanguage.googleapis.com/ |
Trailing slash is normalized at registration |
MaxQueueAttempts |
8 |
Retryable failures before a queued request dead-letters (≈ 20 min of backoff) |
DrainIntervalSeconds / DrainBatchSize |
5 / 4 |
Queue drain tick cadence; one claim per item, never a batch claim |
RequestTimeoutSeconds |
120 |
HTTP client timeout; the claim lease is this plus 180 s |
CompletedRetentionDays |
90 |
GenAiRequestRetentionJob deletes finished rows older than this; 0 keeps them forever |
The template ships the adapter with no domain-specific request kind, context source, or result handler wired up — IGenAiClient.GenerateTextAsync/GenerateAsync<T> work standalone, and the queue drains Generic-kind requests correctly with nothing registered to receive them. See "Adding GenAI to a Feature" below.
- The container listens on port 8080 (
ASPNETCORE_HTTP_PORTS), terminate TLS at your reverse proxy or load balancer and forwardX-Forwarded-For/X-Forwarded-Proto. SetNetwork__KnownProxiesorNetwork__KnownNetworksso only your proxy can supply those headers. - Run migrations either by setting
Database__MigrateOnStartup=trueon a single instance or by runningdotnet ef database update(or an EF migration bundle) in your release pipeline. GET /healthis unauthenticated and suitable for liveness and readiness probes.- Set
Redis__ConnectionStringwhen running more than one instance so rate limits and the permission cache are shared. Without it the API logs a warning and keeps both in process. - Deactivated accounts are anonymized immediately and hard-deleted by a daily job 30 days later (
AuthConfiguration.RemoveAfterFlagging), which frees the e-mail address for re-registration.
| Method | Endpoint | Auth | Description |
|---|---|---|---|
POST |
/register |
— | Create a new account (Password mode) |
POST |
/login |
— | Authenticate with email/username + password (Password mode) |
POST |
/store/sign-in |
— | Sign in or register with an Apple/Google ID token (Store mode) |
POST |
/refresh |
— | Refresh the access token via cookie |
POST |
/logout/device |
✅ | Log out current device (POST only) |
POST |
/logout |
✅ | Log out all devices (POST only) |
GET |
/self |
✅ | Get current user + permissions |
GET |
/preferences |
✅ | Get user preferences |
GET |
/availability/email |
— | Check email availability (Password mode) |
GET |
/availability/username |
— | Check username availability (Password mode) |
PATCH |
/change/password |
✅ | Change password (requires current) (Password mode) |
PATCH |
/change/username |
✅ | Change username |
PUT |
/me/reactivate |
— | E-mail a reactivation link to a deactivated account (always 200) |
POST |
/me/reactivate/confirm |
— | Restore the account with the e-mailed link |
DELETE |
/me/delete |
✅ | Deactivate & anonymize account |
POST |
/heartbeat |
✅ | Report page activity |
POST |
/register/admin |
— | Create an administrator with the Security__AdminPassword secret (Password mode, 404 when unset) |
POST |
/admin/promote |
✅ | Grant the Administrator tag to the signed-in user with the secret (404 when unset) |
| Method | Endpoint | Auth | Description |
|---|---|---|---|
POST |
/confirm/send |
✅ | Send confirmation email |
POST |
/confirm |
— | Confirm email with token |
POST |
/forgot-password/send |
— | Send password reset email |
POST |
/forgot-password |
— | Reset password with token |
POST |
/change-email/send |
✅ | Request email change |
POST |
/change-email |
✅ | Confirm email change |
| Method | Endpoint | Auth | Description |
|---|---|---|---|
GET |
/me |
✅ | Get own profile |
GET |
/u/{username} |
— | Get public profile |
PUT |
/u/{username}/update/core |
✅¹ | Update bio, headline, location |
PATCH |
/me/update/avatar |
✅ | Upload profile picture (multipart file, max 5 MB; re-encoded to 512px WebP; 501 when Storage__Bucket is unset) |
PATCH |
/{id}/update/visibility |
✅¹ | Toggle profile visibility |
DELETE |
/{id}/delete |
✅¹ | Wipe profile data (GDPR) |
| Method | Endpoint | Auth | Description |
|---|---|---|---|
GET |
/ |
✅ | Inbox page; ?before=<seq>&pageSize=&actor=id|username|both |
GET |
/badge |
✅ | Unread count from the read watermark |
POST |
/read |
✅ | Move the watermark; ?upTo=<seq> or everything |
POST |
/actions |
✅ | Run a registered action { type, args }, both built-ins take { seq }: Acknowledge resolves the row, RevokeSessions also signs out every other device; 409 when the button is stale or the type does not offer that action |
GET |
/events |
✅ | SSE stream (notification, badge, read, resolved, resync, : ping); honours Last-Event-ID |
GET |
/preferences |
✅ | Per-category preferences, defaults materialised in the response only |
PUT |
/preferences |
✅ | Update one category |
Every endpoint returns 501 when Notifications__Enabled is false; /events also when Notifications__Stream__Enabled is false; the preference endpoints also when Notifications__Preferences__Enabled is false.
| Method | Endpoint | Auth | Description |
|---|---|---|---|
GET |
/health |
— | Liveness and database readiness |
GET |
/openapi/v1.json |
— | OpenAPI document (Development only) |
| Method | Endpoint | Auth | Description |
|---|---|---|---|
GET |
/dashboard/summary |
✅² | Full dashboard (growth, engagement, health) |
GET |
/dashboard/user-growth |
✅² | User registration stats |
GET |
/dashboard/system-health |
✅² | Flagged/banned user counts |
GET |
/dashboard/users/tag/{tag} |
✅² | List users by tag name |
GET |
/dashboard/audit/{username} |
✅² | User audit log |
GET |
/u/{username} |
✅² | Get user management view |
DELETE |
/u/{username}/ban |
✅² | Ban user with reason |
PATCH |
/u/{username}/unban |
✅² | Unban user |
POST |
/u/{username}/notify |
✅² | Send a SystemNotice { message } (≤ 500 chars) to the user; the caller is the actor. Free text is stored unencrypted in Args, so keep PII out of it |
¹ Owner or user with
Users.Updatepermission
² Requires specific system permissions (e.g.,System.AuditLogs.View)
-
Create a folder under
Features/YourFeature/with the standard subfolders:Features/YourFeature/ ├── Controllers/ ├── Services/ ├── Transfer/ ├── Responses/ ├── Validation/ ├── Entities/ (if new DB tables needed) └── Utilities/ (if feature-specific helpers needed) -
Register your service in
Program.csunder the#region Servicesblock. -
If your feature needs new permissions, add entries to
TagConstants,PermissionIds,PermissionDictionary, andAppPermissionConfiguration.
AddBuiltInNotifications() registers these types and both actions. None of them carries a navigation target; the Security category cannot be muted (the dispatcher ignores a stored mute and PUT /preferences rejects inApp: false for it).
| Type | Raised by | Category | Actor | Actions |
|---|---|---|---|---|
SystemNotice |
POST /api/admin/u/{user}/notify, POST /api/admin/notify |
System | admin | Acknowledge |
NewDeviceLogin |
Password or store sign-in from a device with no refresh token | Security | – | Acknowledge, RevokeSessions |
SessionRevoked |
A rotated refresh token presented again after the leeway (coalesced) | Security | – | Acknowledge, RevokeSessions |
PasswordChanged |
PATCH /api/auth/change/password, POST /api/email/forgot-password ({ reset } says which) |
Security | – | – |
EmailChanged |
POST /api/email/change-email |
Security | – | RevokeSessions |
PromotedToAdministrator |
POST /api/auth/admin/promote (first time only) |
Security | – | Acknowledge |
BanLifted |
PATCH /api/admin/u/{user}/unban |
Account | admin | – |
SubscriptionActivated |
PATCH /api/admin/u/{user}/subscription/confirm/{tier} ({ tier }) |
Account | – | – |
ProfileModerated |
Core update, visibility toggle or wipe of someone else's profile ({ change, isPublic? }) |
Account | caller | – |
Every row is queued before the domain SaveChangesAsync, so it commits with the change that caused it. RevokeSessions keeps the device that clicked it (matched by user agent and IP blind index like device logout) and removes every other refresh token; when the current device cannot be matched it removes all of them.
- Append a value to
NotificationType(andNotificationCategory/NotificationActionType/NotificationTargetEntityif needed). Values are permanent: append only, never renumber, never reuse. - Derive from
NotificationDescriptorBase(Features/Notifications/Utilities/Descriptors/) and set icon, category, the actions it offers andRender(row); override the aggregate key, plural template, coalescing orResolveTarget(row)only when the type needs them. ReadArgsthroughNotificationArgs. Names come fromrow.ActorName; never copy a name intoArgs. Free-textArgs(as used bySystemNoticeDescriptor) carry the same PII risk as a copied name and are stored unencrypted and untouched by key rotation, so avoid putting user-identifying text there either. - Derive from
NotificationActionBase(Features/Notifications/Utilities/Actions/) for each new action. The base reads{ seq }, loads the caller's unresolved row, answers409when the row is resolved or its descriptor does not list the action, runs yourApplyAsyncoverride, then stampsResolvedAtand saves.AcknowledgeActionis the base with no override;RevokeSessionsActionshows a side effect. - Register both in
Program.csafter the built-ins:A missing descriptor or handler fails the boot, not the first notification.builder.Services.AddNotifications(builder.Configuration) .AddBuiltInNotifications() .AddType<FollowRequestDescriptor>(NotificationType.FollowRequest) .AddAction<AcceptFollowAction>(NotificationActionType.AcceptFollow);
- Raise it from any service through
INotificationDispatcher.QueueAsync(recipients, type, actorId, args). It adds to the change tracker and does not save; the row commits with your transaction, and delivery is published only after that commit.
- Add the field to your entity
- In
AppDbContext.OnModelCreating, add a value converter using_encryptor.Encrypt/Decrypt - If the field needs to be searchable, add a corresponding
*Indexcolumn and compute it with_encryptor.GenerateBlindIndexinSaveChangesAsync
The adapter (Features/GenAi/) is a provider-agnostic gateway for generative-model calls — see docs/superpowers/specs/2026-09-10-genai-adapter-design.md for the full design and its invariants.
- A one-off call: inject
IGenAiClientand callGenerateTextAsyncorGenerateAsync<T>(structured output, schema derived fromT). No retry — the caller sees the failure and decides. - Queued work: append a
GenAiRequestKindmember, build aGenAiPrompt, call_enqueuer.Enqueue<T>(kind, model, prompt, subjectId)on the caller's ownAppDbContext(it adds without saving — your ownSaveChangesAsynccommits it atomically with the domain change), then write anIGenAiResultHandlerin your feature'sUtilities/that looks up its row byrequest.Id, returns early if already terminal, and handles both success and terminal failure. One DI line. - Domain data in a prompt: append a
GenAiContextSubjectTypemember and anIGenAiContextSourcein your feature'sUtilities/, built from the same response DTOs the requesting user couldGET(never raw entities), returningnullwhen they may not see the subject. One DI line. - A model:
GenAiModel.Xplus aGenAiModelCatalog.Resolvearm — the switch has no default, so an unmapped member is a compiler warning, not a runtime surprise.
Edit Configuration/RateLimitValues.cs. Each policy is a named fixed-window limiter partitioned per client (authenticated user id, otherwise remote IP) and registered in RegisterAllPolicies(). Apply to endpoints with [EnableRateLimiting(nameof(RateLimits.YourPolicy))]. Rejections return the standard envelope with status 429 and a Retry-After header.
- External services in tests. The suite runs against in-memory fallbacks. Tests marked with
TEST_REDIS_CONNECTIONandTEST_S3_ENDPOINTrun against real Redis and MinIO; the CI workflow starts both and runs them on every push. - Avatars are public objects. The bucket (or CDN) serves them by URL; keys contain the user id and a random suffix. Deactivation deletes the object, the purge job deletes leftovers.
- Re-encryption throughput. The job rewrites 200 rows per batch per table and stops with an error if a batch makes no progress, so a misconfigured key ring cannot loop forever.
- Reuse detection depth. Five rotated hashes are kept per device; anything older is rejected without revoking the session.
- Notifications never have PII injected by the framework. The dispatcher, entity, reader and renderer only ever pass
Argsthrough verbatim; none of them join in a name, email or other PII on your behalf, soArgsneeds no key-ring column and key rotation never touches it. That is not the same as an enforced guarantee:Argsis free-form JSON, and a descriptor (likeSystemNoticeDescriptor, which stores arbitrary free text) is only as PII-free as what the calling code puts into it. Hosts are responsible for not putting PII intoArgsthemselves. TheNotificationstable is created withfillfactor = 90andautovacuum_vacuum_scale_factor = 0.02; the second is what keeps the badge count index-only on a churning table. - Notification configuration is read once at startup.
Enabled,Retention:EnabledandStream:Enableddecide, at registration time, which background services and dispatcher implementation are wired up (the real dispatcher vs. a disabled no-op, whetherNotificationTrimService/NotificationHeartbeatrun at all). They are read viaIConfiguration, notIOptionsMonitor, so changing them requires a process restart — they are not hot-reloadable. - A fresh database bootstrap can fail before reaching the Notifications migration.
AvatarUrlwas never migrated fromUserProfilestoUsers, which is a pre-existing gap unrelated to Notifications. Ifdotnet ef database updatefails during the earlierRotationEncryptionAndAvatarsmigration, that is why — it needs a separate fix outside this feature, not something wrong with20260909004241_Notifications. - Postgres in tests.
TEST_POSTGRES_CONNECTIONruns the migration against a disposable database and proves the identity-in-composite-key, hash index and table options; CI starts the container.
| Layer | Technology |
|---|---|
| Runtime | .NET 10 |
| Framework | ASP.NET Core (Minimal Hosting) |
| Database | PostgreSQL 17 via Npgsql + EF Core 10 |
| Identity | ASP.NET Core Identity |
| Auth | JWT Bearer (cookie-based) |
| Validation | FluentValidation 12 + SharpGrip AutoValidation |
| MailKit + MimeKit | |
| Caching | IMemoryCache (in-process) |
| Containerization | Docker (multi-stage) |