📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the ASP.NET Core Data Protection API? Explain what uses it (cookies, antiforgery, TempData), how the key ring works, purposes and IDataProtector, key lifetime and rotation, and how you persist and protect keys when an app runs on several instances, for example with Azure Blob Storage and Key Vault.

Covers ASP.NET Core Data Protection: the consumers that depend on it, the key ring and automatic 90-day rotation, purpose strings, time-limited protectors, default key storage locations, and production configuration with PersistKeysToAzureBlobStorage, ProtectKeysWithAzureKeyVault and SetApplicationName.

Mid-Level Theory Intermediate aspnet-core azure-key-vault cookies cryptography data-protection security

🎯 Key points

  • Data Protection encrypts and authenticates app payloads: auth cookies, antiforgery tokens, TempData, OIDC state, Identity tokens
  • Default algorithms: AES-256-CBC with HMACSHA256 (authenticated), subkeys derived per purpose
  • Key ring: 90-day default lifetime, next key created automatically before expiry; expired keys still unprotect, revoked keys don't
  • Purposes isolate consumers: CreateProtector("Orders.Export.v1") can't unprotect another purpose's payload; ToTimeLimitedDataProtector for expiring tokens
  • Default key storage is machine-local or ephemeral in containers: keys lost on redeploy
  • Production: PersistKeysToAzureBlobStorage + ProtectKeysWithAzureKeyVault, same SetApplicationName across instances and slots
  • Back up the key repository (soft delete, resource lock): losing it invalidates every session and outstanding token
  • Cheap at runtime: the ring is cached and refreshed about every 24 hours, so no per-request I/O; not for long-term data at rest

⏱ 30-second answer

Data Protection is ASP.NET Core's built-in API for encrypting and authenticating short-lived payloads the app hands to clients and gets back. It protects authentication cookies, antiforgery tokens, TempData, OIDC state and Identity tokens. You call IDataProtectionProvider.CreateProtector("purpose"), and the purpose string isolates consumers so one feature's payload can't be replayed into another.

Under the hood is a key ring: keys with a 90-day default lifetime, rotated automatically, old keys retained to unprotect older payloads. The production trap is storage: by default keys live on the local machine or, in a container, in an ephemeral folder, so each instance and each redeploy has different keys and users get logged out. Fix it with PersistKeysToAzureBlobStorage, ProtectKeysWithAzureKeyVault and the same SetApplicationName everywhere. Don't use it for long-term data at rest.

🗣 Full answer (senior)

How I would answer this in an interview

"Data Protection is the cryptography layer ASP.NET Core uses whenever it gives a client something it must get back unmodified: the authentication cookie, antiforgery tokens, TempData in cookies, the OpenID Connect state and nonce, and Identity's email confirmation and password reset tokens. I can use it directly too: inject IDataProtectionProvider, create a protector with a purpose string like "Invoices.DownloadLink.v1", and call Protect and Unprotect. The purpose is mixed into key derivation, so a payload protected for one purpose won't unprotect under another, which stops a password-reset token being reused as a download link.

The mechanics are a key ring. Each key has a 90-day lifetime by default. The system creates the next key ahead of expiry, new payloads use the default key, and the key id is in every payload header so older payloads still unprotect with older keys. Each payload is AES-256-CBC encrypted and HMACSHA256 authenticated with subkeys derived from the master key and the purpose.

The thing that bites teams is where the keys live. On IIS they're in the registry or user profile; in a Linux container they end up in a folder that disappears with the container, and ASP.NET Core logs a warning about it. With three instances behind a load balancer, each has its own key ring, so a cookie issued by instance A fails on instance B. In Azure I configure PersistKeysToAzureBlobStorage so every instance shares the ring, ProtectKeysWithAzureKeyVault so the key XML is encrypted at rest with a Key Vault key, and an explicit SetApplicationName so a new deployment slot or container name doesn't isolate the keys.

The mistake I see is using Data Protection to encrypt database columns for years. If keys are revoked or the ring is lost, that data is gone. It's designed for transient payloads."


Who uses it

Consumer What is protected Symptom when keys aren't shared
Cookie authentication The authentication ticket Users logged out on redeploy or between instances
Antiforgery Cookie token and request token AntiforgeryValidationException, 400s on form posts
TempData (cookie provider) TempData values TempData silently empty
OIDC handler state, nonce cookie "Correlation failed" / "Unable to unprotect the message.State"
Identity token providers Email confirmation, password reset tokens "Invalid token"

Key storage options

Host Default Production choice
IIS Registry (HKLM) or user profile Shared storage if web farm
Azure App Service %HOME%\ASP.NET\DataProtection-Keys, shared across instances of one app but not slots Blob + Key Vault for slots and multiple apps
Containers / AKS In-memory or ephemeral folder Blob Storage + Key Vault, or a Redis/EF Core repository

Production example

After a move to [AKS with three replicas], [about a third] of form posts failed antiforgery validation and users were logged out on every deployment. Sharing the key ring in Blob Storage protected by Key Vault took the antiforgery error rate from [around 30%] to [effectively zero] the same day.

🔍 What the interviewer is checking

Checks whether the candidate understands what Data Protection does, how the key ring works and how to configure it correctly for multi-instance production.

Green flags

  • Lists the framework consumers (cookies, antiforgery, OIDC, TempData)
  • Explains key ring rotation and key ids in payloads
  • Configures shared persistence, Key Vault protection and application name
  • Knows not to use it for long-term data

Red flags

  • Never heard of it, or thinks cookies are just signed
  • Doesn't know keys are local by default
  • Uses it as general-purpose database encryption

📚 Learn in depth

1. Payload format

| magic header (4) | key id GUID (16) | encrypted payload (IV + ciphertext + HMAC) |
          ^ tells Unprotect which key in the ring to use

The master key is never used directly. For each payload: subkeys = KDF(masterKey, purposes, random key modifier) using SP800-108 CTR-HMACSHA512, then AES-256-CBC + HMACSHA256 by default (or AES-GCM via UseCryptographicAlgorithms).

2. The key ring lifecycle

day 0    key A created, default
day 88   key B created (activation date = A's expiry)
day 90   B becomes default; A expired but kept for Unprotect
revoked  key can no longer unprotect anything

Keys are XML files in the repository (file system, Blob, Redis, EF Core DataProtectionKeys table). The key encryptor protects the XML at rest (DPAPI, a certificate, or Key Vault).

3. Purposes and isolation

CreateProtector("A").CreateProtector("B") is the purpose chain ["A", "B"]. The application name (or by default the content root path) is the root discriminator, which is why two apps sharing a ring still can't read each other's payloads unless they set the same SetApplicationName, and why changing paths between deployments breaks old payloads.

4. Time-limited protectors

protector.ToTimeLimitedDataProtector().Protect(value, lifetime: TimeSpan.FromMinutes(15)) embeds an expiry checked on unprotect. Good for signed download links and invitation tokens.

5. Production configuration

  • Packages: Azure.Extensions.AspNetCore.DataProtection.Blobs and Azure.Extensions.AspNetCore.DataProtection.Keys.
  • The managed identity needs blob read/write on the container and wrap/unwrap on the Key Vault key.
  • Key Vault is called on startup and when the ring refreshes (about every 24 hours), not per request.
  • If the key file is deleted, the app creates a new ring and every cookie is invalid: back up the container and protect it from deletion.

Try it yourself

  1. Run an app in Docker, sign in, restart the container, and observe the logout and the startup warning about ephemeral keys.
  2. Configure PersistKeysToFileSystem on a mounted volume and repeat.
  3. Switch to Blob + Key Vault and inspect the key XML (the encryptedSecret element).
  4. Protect a value with purpose A and try to unprotect with purpose B.
  5. Build a time-limited download link and verify it fails after expiry.

💻 Code

Production Data Protection setup for multiple instances, plus a purpose-scoped, time-limited protector for download links.

// Program.cs
using Azure.Identity;
using Microsoft.AspNetCore.DataProtection;

var credential = new DefaultAzureCredential(); // managed identity in Azure

builder.Services.AddDataProtection()
    .SetApplicationName("contoso-portal")              // same value on every instance and slot
    .PersistKeysToAzureBlobStorage(
        new Uri(builder.Configuration["DataProtection:BlobUri"]!), credential)
    .ProtectKeysWithAzureKeyVault(
        new Uri(builder.Configuration["DataProtection:KeyUri"]!), credential)
    .SetDefaultKeyLifetime(TimeSpan.FromDays(90));    // the default, shown explicitly

builder.Services.AddSingleton<DownloadLinks>();
using Microsoft.AspNetCore.DataProtection;

namespace Portal.Documents;

public sealed class DownloadLinks(IDataProtectionProvider provider)
{
    // Purpose string versioned so a format change doesn't accept old links.
    private readonly ITimeLimitedDataProtector _protector =
        provider.CreateProtector("Portal.Documents.DownloadLink.v1").ToTimeLimitedDataProtector();

    public string Create(Guid documentId, string userId) =>
        _protector.Protect($"{documentId:N}|{userId}", lifetime: TimeSpan.FromMinutes(15));

    public (Guid DocumentId, string UserId)? Read(string token)
    {
        try
        {
            var parts = _protector.Unprotect(token).Split('|');
            return (Guid.ParseExact(parts[0], "N"), parts[1]);
        }
        catch (System.Security.Cryptography.CryptographicException)
        {
            return null; // tampered, expired or from another purpose
        }
    }
}

⚠ Common mistakes

  • Mistake: Leaving default key storage in containers. Why it is wrong: keys are lost on every restart, logging users out and breaking antiforgery. Instead: persist keys to shared storage.
  • Mistake: Running several instances or slots without a shared ring and application name. Why it is wrong: payloads issued by one instance fail on another. Instead: shared repository plus SetApplicationName.
  • Mistake: Persisting keys without protecting them at rest. Why it is wrong: anyone with blob read access can forge auth cookies. Instead: ProtectKeysWithAzureKeyVault or a certificate.
  • Mistake: Using Data Protection for long-term database encryption. Why it is wrong: lost or revoked keys make data permanently unreadable. Instead: envelope encryption with Key Vault or Always Encrypted.
  • Mistake: Reusing one purpose string everywhere. Why it is wrong: tokens from one feature can be replayed in another. Instead: specific, versioned purposes.
  • Mistake: Deleting the key blob to "reset" things. Why it is wrong: every session and outstanding token becomes invalid. Instead: revoke specific keys via IKeyManager if compromised, and back up the container.
  • Mistake: Ignoring the startup warning "No XML encryptor configured" or "keys stored in a directory that may not be persisted". Why it is wrong: it predicts the production incident. Instead: treat it as a deployment check.

🏛 Senior insight: trade-offs

Data Protection is shared infrastructure, so treat the key ring as a production dependency: its storage needs access control, backup and monitoring, and its application name is part of your compatibility contract. If you ever suspect the ring leaked, revoking keys logs everyone out and invalidates all tokens, which is the correct trade-off but needs a comms plan.

Repository When it fits Cost When not
Azure Blob + Key Vault Azure, multiple instances or slots Two dependencies at startup Offline or on-prem only
EF Core PersistKeysToDbContext You already have a shared database Keys in the same DB as data When DB compromise must not enable cookie forgery (add an encryptor)
Redis Existing Redis, containers Redis persistence must be on Redis without persistence
File system on a shared volume On-prem web farms Volume management Ephemeral containers

Measure: unprotect failures in logs (Microsoft.AspNetCore.DataProtection category), antiforgery 400 rate after deployments, and alerts if the key blob changes unexpectedly.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the authentication cookie is protected by Data Protection. Why: Checks cookie authentication details: flags, expiry and what the cookie contains.
    How to answer

    After a successful login the app calls HttpContext.SignInAsync: the cookie handler serialises the ClaimsPrincipal into an authentication ticket, encrypts and signs it with Data Protection, and sends it as a cookie. On each request the handler decrypts the cookie and rebuilds HttpContext.User, with no database call.

    • Flags: HttpOnly (JavaScript can't read it), Secure (HTTPS only), SameSite=Lax by default (not sent on most cross-site requests).
    • Expiry: ExpireTimeSpan (default 14 days) with sliding expiration that reissues the cookie once half the window has passed; IsPersistent decides whether it survives closing the browser.
    • Keys: every instance must share the Data Protection key ring, or cookies issued by one server can't be read by another.

    The trade-off: a self-contained cookie is fast and stateless, but you can't revoke it without extra checks or a server-side ticket store.

  2. When: Candidate mentions signed download links or tokens. Why: Checks when HMAC is a simpler alternative for signed payloads shared with other systems.
    How to answer

    HMAC-SHA256 is a keyed hash: the sender computes HMAC(secret, message) and you recompute it with the same secret. A match proves the body wasn't altered and came from someone holding the secret; it does not encrypt anything.

    Three details make verification correct. Hash the raw request bytes exactly as received, because re-serialising JSON changes whitespace and ordering. Compare with CryptographicOperations.FixedTimeEquals, because an early-exit comparison leaks how many leading bytes matched through timing. And sign a timestamp with the payload and reject old ones (Stripe uses a 5-minute default) so a captured request can't be replayed; store event ids for idempotency too. Keep the secret in Key Vault and accept two during rotation. Use asymmetric signatures instead when many parties must verify but shouldn't be able to forge.

🛠 Real-world problems: how you handle them

OIDC 'Correlation failed' errors after scaling out
Situation
A [staff portal] using Entra ID sign-in on [Azure App Service] was scaled from one to [four instances] and given a staging slot for swaps.
Signals
Intermittent `Correlation failed` and `Unable to unprotect the message.State` errors during sign-in, spiking after each slot swap; users reported having to sign in twice.
Investigation
Read the authentication and Data Protection logs in Application Insights; noticed the warning that keys were stored per slot; compared the key ids in failing payloads with the key ring on each slot; reproduced by signing in on staging and completing the callback after a swap.
Resolution
Configured `PersistKeysToAzureBlobStorage` and `ProtectKeysWithAzureKeyVault` with a shared container and key, and an explicit `SetApplicationName`, so both slots and all instances used one ring.
Prevention
A deployment checklist item and an integration test that protects with one host and unprotects with another; alert on Data Protection unprotect errors; the container protected by a resource lock and soft delete.

How to tell it (STAR)

**S:** At [company] our [staff portal] started throwing 'Correlation failed' during sign-in after we scaled out and added a staging slot. **T:** I had to find out why sign-in broke intermittently and fix it before [the next release]. **A:** From the logs I saw the OIDC state couldn't be unprotected, compared key ids, and found each slot had its own Data Protection key ring. I moved the ring to Blob Storage protected with a Key Vault key, set a fixed application name, and added a test that unprotects across two hosts. **R:** Sign-in failures dropped from [about 4%] to [under 0.01%], and slot swaps no longer logged anyone out.

↩ Usually asked after

More in Cryptography

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me