The new server is built. The app is deployed. DNS is flipped. Every user is signed out, every half-finished form fails its anti-forgery check, and every password reset link you emailed yesterday no longer works.
Nothing is broken in the code. The app simply lost its keys. ASP.NET Core Data Protection was quietly storing them somewhere tied to the old machine, and nobody wrote that down because nobody ever had to configure it. With Windows Server 2016 reaching end of extended support on January 12, 2027, a lot of teams are about to find this out the hard way. Let's make sure yours isn't one of them. Let's dive in!
What Data Protection Is Doing for You
You may never have called the Data Protection APIs directly, but your app uses them all the time. ASP.NET Core relies on them to protect authentication cookies, antiforgery tokens, the cookie-based TempData provider, and the tokens behind ASP.NET Core Identity links such as password resets and email confirmations. If your own code calls CreateProtector to encrypt values, that is Data Protection as well.
All of that depends on a key ring. Keys have a 90-day lifetime by default, and the app rolls to a new key automatically. Old keys stay in the ring so data protected with them can still be read. That works perfectly, right up until the app starts reading from a different key ring.
Where Your Keys Live If You Never Configured Them
When you do not configure a location, the framework picks one based on the environment. Microsoft documents the order in Data Protection key management and lifetime:
- Azure App Service: keys go to
%HOME%\ASP.NET\DataProtection-Keys, shared across instances in the same deployment slot. Keys are not protected at rest, and each slot has its own key ring, so a staging-to-production swap can sign users out. - User profile available: keys go to
%LOCALAPPDATA%\ASP.NET\DataProtection-Keys, encrypted with DPAPI on Windows. - Hosted in IIS: keys go to a special registry key under HKLM, ACLed to the worker process account and encrypted with DPAPI.
- None of the above: keys are kept in memory only. When the process shuts down, they are gone.
Look at that list from the point of view of a migration. Keys in a local profile folder or a machine registry key, encrypted with DPAPI, are bound to that machine. Copying the site's files to a new server does not bring them along. The in-memory case is worse: that app has been losing its keys on every app pool recycle all along, and the migration is just the first time anyone notices.
There is a second, quieter trap. By default, ASP.NET Core isolates apps from each other using an application discriminator, and for IIS-hosted apps that value is the app's physical path. Move the site from D:\Sites\Portal to E:\inetpub\portal and the discriminator changes, even if you somehow brought the keys with you.
Step 1: Find Out What You Have Today
Before changing anything, ask the running app. Turn on Information logging for the Data Protection category in appsettings.json (or an environment-specific file) on the current server:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.AspNetCore.DataProtection": "Information"
}
}
}
At startup the Data Protection system logs which key repository it selected. If you see a warning that keys are only held in memory or will not be persisted, stop reading and fix that first; your users have been getting signed out after every recycle.
Then log the two values that matter for a move. This goes after builder.Build() in Program.cs:
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.Extensions.Options;
var app = builder.Build();
var protection = app.Services.GetRequiredService<IOptions<DataProtectionOptions>>().Value;
var keyManagement = app.Services.GetRequiredService<IOptions<KeyManagementOptions>>().Value;
app.Logger.LogInformation(
"Data Protection discriminator: {Discriminator}. Explicit key repository: {Repository}",
protection.ApplicationDiscriminator,
keyManagement.XmlRepository?.GetType().Name ?? "none (default discovery)");
If the repository line says "none," the app is relying on the defaults above. If the discriminator is a physical path, write it down. You will need it in a minute.
While you are at it, find out whether your own code protects data that outlives a request:
git grep -n -E "IDataProtectionProvider|CreateProtector|ToTimeLimitedDataProtector"
Protecting a value for a link or a cookie is fine. Protecting a value and storing it in a database is a different conversation, which I come back to below.
Step 2: Give the Keys a Real Home
The fix is to choose the key location and the application name yourself, so neither depends on the machine. Microsoft's guidance is that when you set an explicit location, the default encryption at rest is turned off, so you should also choose how the keys are protected. Two setups cover most of the apps I see.
Moving to Azure: Blob Storage plus Key Vault
Add the Azure.Extensions.AspNetCore.DataProtection.Blobs, Azure.Extensions.AspNetCore.DataProtection.Keys, and Azure.Identity packages. If you still reference the older Microsoft.AspNetCore.DataProtection.AzureStorage or Microsoft.AspNetCore.DataProtection.AzureKeyVault packages, Microsoft recommends removing them in favor of these.
using Azure.Core;
using Azure.Identity;
using Microsoft.AspNetCore.DataProtection;
var builder = WebApplication.CreateBuilder(args);
var dp = builder.Configuration.GetSection("DataProtection");
TokenCredential credential = builder.Environment.IsProduction()
? new ManagedIdentityCredential(dp["ManagedIdentityClientId"])
: new DefaultAzureCredential();
builder.Services.AddDataProtection()
.SetApplicationName(dp["ApplicationName"]!)
.PersistKeysToAzureBlobStorage(new Uri(dp["KeyBlobUri"]!), credential)
.ProtectKeysWithAzureKeyVault(new Uri(dp["KeyVaultKeyId"]!), credential);
And the matching configuration:
{
"DataProtection": {
"ApplicationName": "customer-portal",
"KeyBlobUri": "https://contosokeys.blob.core.windows.net/data-protection/keys.xml",
"KeyVaultKeyId": "https://contoso-vault.vault.azure.net/keys/data-protection",
"ManagedIdentityClientId": "00000000-0000-0000-0000-000000000000"
}
}
A few details from the documentation that are easy to miss. With a managed identity, you do not create the key file yourself; the framework creates it. The identity needs the Storage Blob Data Contributor role on the storage and the Key Vault Crypto User role on the vault. If you plan to turn on automatic rotation for the Key Vault key, use a versionless key identifier like the one above and never delete old Key Vault key versions, because older Data Protection keys still reference them.
This setup also fixes the App Service slot problem. Every slot reads the same key ring, so a swap no longer signs people out.
Staying on-premises: a database plus a certificate
If the app is moving to a newer Windows Server rather than to the cloud, a database you already back up is a reasonable home for the keys. Add Microsoft.AspNetCore.DataProtection.EntityFrameworkCore and give the keys their own context:
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
public class KeysDbContext(DbContextOptions<KeysDbContext> options)
: DbContext(options), IDataProtectionKeyContext
{
public DbSet<DataProtectionKey> DataProtectionKeys => Set<DataProtectionKey>();
}
builder.Services.AddDbContext<KeysDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("Keys")));
builder.Services.AddDataProtection()
.SetApplicationName("customer-portal")
.PersistKeysToDbContext<KeysDbContext>()
.ProtectKeysWithCertificate(builder.Configuration["DataProtection:CertificateThumbprint"]!);
Create the table with a migration (dotnet ef migrations add AddDataProtectionKeys --context KeysDbContext, then dotnet ef database update --context KeysDbContext). Install the certificate, with its private key, on every server that runs the app. A certificate that exists on only one machine just moves the original problem somewhere else.
About the application name
Pick a stable name, such as customer-portal, and use it everywhere this app runs. There is one caveat. Changing the discriminator is itself a key change, so the first deployment with SetApplicationName will not be able to read payloads protected under the old path-based value. That is fine if you are already switching key locations in the same deployment, which is the plan below. If for some reason you need to keep the existing keys and only lock the name, set the name to the exact value you logged in Step 1.
Step 3: Make Production Refuse to Run Without It
Configuration that lives in one place gets lost in the next refactor. I like a small guard that stops a production instance from starting if someone removes the explicit key setup:
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.Extensions.Options;
var app = builder.Build();
if (app.Environment.IsProduction())
{
var keyOptions = app.Services.GetRequiredService<IOptions<KeyManagementOptions>>().Value;
if (keyOptions.XmlRepository is null)
{
throw new InvalidOperationException(
"Data Protection has no explicit key repository. " +
"Keys would be tied to this machine or lost on restart.");
}
}
A failed startup in a deployment slot is a much better day than a successful deployment that signs out every customer.
Step 4: Plan the Cutover So the Migration Is Boring
Here is the honest trade-off. Keys that DPAPI protected in the old server's registry or profile can't simply be copied to the new location. So when you switch to the new key ring, data protected with the old keys becomes unreadable. You can't avoid that moment, but you can choose when it happens. My recommendation is to separate it from the server move:
- Deploy the new Data Protection configuration to the old server first, in a quiet window. Users sign in once more, any open forms need a refresh, and outstanding password reset and email confirmation links stop working. Tell your support team before, not after.
- Confirm the new key ring is in use. Check the startup log from Step 1, and check that a key now exists in the blob or the
DataProtectionKeystable. - Migrate the server whenever you are ready. The new server reads the same key ring with the same application name. Sign in on the old server, move traffic to the new one, and you should still be signed in. That is your test.
If Step 1 turned up code that stores protected values in a database, do not start the cutover until that data has been handled. Those values can only be read with the old keys, so they have to be unprotected and re-protected (or simply re-created) while the old key ring is still available. That is a small project of its own, and it is far easier before the switch than after.
The Conversation for Leaders
If you are planning Windows Server 2016 migrations, add one line to every app's checklist: "Where are this app's Data Protection keys, and who chose that location?" If the answer is "the defaults," the migration plan needs one more deployment in it. That deployment costs an hour. Skipping it costs a support queue full of "why was I logged out?" tickets on cutover day.
Your Next Step
Add the two log lines from Step 1 to your most important ASP.NET Core app and deploy them this week. In five minutes you will know whether its keys live somewhere that survives a server move, and you will have the discriminator value written down before you need it.
Categories