Data Protection API in ASP.NET Core
Cookies, anti-forgery tokens, and temp-link payloads all need encryption that just works. The ASP.NET Core Data-Protection API (DPAPI) provides a turnkey key-ring, key rotation, and multi-node sync—no crypto PhD required.
Real-Life Analogy: Hotel Master Key System
Every guest key opens one room, but the master opens all. The hotel keeps masters in a tamper-proof lockbox and swaps them yearly. Data-Protection does the same: app secrets are encrypted with a rotating master key protected in a secure store.
Core Concepts
- Key Ring – XML files each holding one AES key + creation/expiry dates.
- Key-Encryption-Key (KEK) – how the key files are themselves protected (DPAPI-NG, X.509 cert, Azure Key Vault, AWS KMS).
- Purpose String – isolates cryptos for different features:
TimeLimitedDataProtector("ResetPwd")
≠("AntiForgery")
.
Configuring in Program.cs
builder.Services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo("/var/keys"))
.ProtectKeysWithAzureKeyVault(
keyIdentifier: "https://kv.vault.azure.net/keys/dp-key",
clientId: cfg.ClientId,
clientSecret: cfg.Secret)
.SetDefaultKeyLifetime(TimeSpan.FromDays(90));
Encrypting Arbitrary Payloads
var protector = dp.CreateProtector("InvoiceLinks");
var token = protector.Protect($"{userId}|{invoiceId}|{DateTime.UtcNow}");
var data = protector.Unprotect(token);
Time-Limited Tokens
var tlp = dp.CreateProtector("PasswordReset")
.ToTimeLimitedDataProtector();
var link = tlp.Protect(userId.ToString(),
lifetime: TimeSpan.FromHours(2));
Scaling Across Servers
- Put key-ring in shared file-share, Redis, or cloud blob.
- Ensure all pods/VMs share identical
ApplicationName
. - Automate cert/KEK rollovers via CI pipeline.
Hardening Checklist
- Restrict key-ring directory perms to the app’s user.
- For containers, mount
/var/keys
as persistent volume. - Do not commit key-ring to source control.
Final Thoughts
DPAPI removes crypto foot-guns: pick a key store, set rotation, and let the framework guard your cookies and links like a seasoned concierge.