In ASP.NET Core, what is the Data Protection API for, and why does IDataProtectionProvider.CreateProtector require a purpose string?
answer
- cookies, antiforgery, TempData already use it
- singleton IDataProtectionProvider from AddDataProtection
- purposes folded into authenticated data
- string Protect returns base64url text
- CryptographicException on any mismatch
basics
~20 sASP.NET Core's Data Protection API encrypts and authenticates payloads that leave the server, such as auth cookies, antiforgery tokens and your own tokens. The purpose string isolates them: a payload protected under one purpose throws CryptographicException when unprotected under another.
solid answer
~40 sData Protection is the framework's built-in authenticated encryption for data that goes to a client and comes back: the cookie authentication handler, antiforgery, the cookie TempData provider and the session middleware all use it. You inject the singleton `IDataProtectionProvider` (registered by `AddDataProtection()`, which those features also call), create a protector with `provider.CreateProtector("TravelSite.BookingLinks.v1")`, and call `Protect` and `Unprotect`; the string overloads return base64url text that is safe in a URL. The purpose chain is part of every payload's authenticated data, so a protector with a different chain cannot read it, and `Unprotect` throws `CryptographicException` for tampered, foreign or undecryptable input. Protectors are thread-safe, so create one and reuse it. It is reversible encryption, not hashing: passwords belong in `PasswordHasher<TUser>` or `KeyDerivation.Pbkdf2`.
code
csharp · 27 linesusing System.Security.Cryptography;
using Microsoft.AspNetCore.DataProtection;
public sealed class BookingLinkService(IDataProtectionProvider provider)
{
private readonly IDataProtector _protector =
provider.CreateProtector("TravelSite.BookingLinks.v1");
public string CreateToken(string bookingReference) =>
_protector.Protect(bookingReference);
public string? ReadToken(string token)
{
try
{
return _protector.Unprotect(token);
}
catch (CryptographicException)
{
return null; // tampered, other purpose, or unknown key
}
}
}
// Program.cs
builder.Services.AddDataProtection();
builder.Services.AddSingleton<BookingLinkService>();go deeper
Recall what Data Protection protects by default, the three calls (CreateProtector, Protect, Unprotect), and that a wrong purpose or tampered input throws CryptographicException.
Explain how the purpose chain becomes authenticated data, why chains are ordinal and ordered, and how the application name isolates apps sharing a key store.
Design purpose strings as versioned contracts, keep untrusted input out of the head of the chain, and handle CryptographicException as invalid input rather than a server error.
Decide which data may live under Data Protection at all, given that payloads die with their keys, and which needs a durable encryption scheme with its own key management.
## What the Data Protection API is ASP.NET Core's **Data Protection API** (namespace `Microsoft.AspNetCore.DataProtection`) is the framework's built-in way to protect a payload that leaves the server and later comes back: a cookie, a hidden form field, a link in an email. A protected payload is **confidential** (the client cannot read it) and **tamper-evident** (any change makes `Unprotect` fail). The system also generates, stores and rotates its own keys, so application code never handles key material. The consumer surface is small: - **`IDataProtectionProvider`**: a singleton registered by `builder.Services.AddDataProtection()`. `AddAuthentication`, `AddAntiforgery`, the MVC view features, `AddSession` and Blazor's server services call `AddDataProtection()` themselves, so most web apps already have it. - **`CreateProtector(string purpose)`**: returns an `IDataProtector` bound to that purpose. An extension overload takes several strings (`CreateProtector("TravelSite", "BookingLinks", "v1")`), and because `IDataProtector` is itself an `IDataProtectionProvider`, calling `CreateProtector` on a protector extends the chain the same way. - **`Protect` / `Unprotect`**: `byte[]` in and out on the interface, plus `string` extension methods that UTF-8 encode the input and return **base64url** text, safe in a query string or cookie. ## Why the purpose string exists One key ring protects everything in the app, so something has to stop a payload made for one feature being accepted by another. That is the job of the **purpose chain**: the purposes are folded into the authenticated data of every payload. 1. A payload protected with `CreateProtector("TravelSite.BookingLinks.v1")` can only be unprotected by a protector with exactly that chain (same strings, same order, ordinal comparison). 2. Handing it to a protector created with `"TravelSite.Unsubscribe.v1"` makes `Unprotect` throw `CryptographicException`, even though the same key protected both. 3. The provider prefixes every chain with the **application name** (by default derived from the content root path), so two apps that share a key store are isolated as well, unless they deliberately set the same name with `SetApplicationName`. Treat a purpose like a contract name: unique to one use, versioned when the payload format changes, and never built only from user input. ## The framework's own purposes | Feature | Purpose chain it creates | |---|---| | Cookie authentication | `Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware`, the scheme name, `v2` | | Antiforgery tokens | `Microsoft.AspNetCore.Antiforgery.AntiforgeryToken.v1` | | Cookie TempData provider | `Microsoft.AspNetCore.Mvc.CookieTempDataProviderToken.v1` | | Session middleware | `SessionMiddleware` | This is why a captured antiforgery token cannot be replayed as an authentication cookie: the purposes differ, so the payloads are not interchangeable. ## Using it in your own code A travel-agency site sends "manage my booking" links. The booking reference in the link must be unreadable and impossible to edit into someone else's reference. The code example shows a service that creates one protector in its constructor and reuses it; registering that service as a singleton is fine because protectors are thread-safe. ## Getting a protector without constructor injection - **From any `IServiceProvider`**: `services.GetDataProtector("TravelSite.BookingLinks.v1")` combines `GetDataProtectionProvider()` and `CreateProtector` in one call. - **Outside a host**, for example a small console tool that must read the site's payloads: `DataProtectionProvider.Create(new DirectoryInfo(path), b => b.SetApplicationName("travel-site"))` builds a provider over the site's key folder. The tool has to use the same application name and purpose chain as the site, or nothing it unprotects will match; with no host there is no content root to fall back on, so set the name explicitly. ## Failure handling and limits - `Unprotect` throws **`CryptographicException`** for tampered input, a different purpose chain, a payload from another application, or a payload whose key is no longer in the key ring. Catch that type specifically and treat the input as invalid (a 400, or a "link no longer valid" page). Catching `Exception` hides real bugs. - It is **reversible encryption**, not hashing. Passwords need a one-way, salted hash such as Identity's `PasswordHasher<TUser>` or `KeyDerivation.Pbkdf2`. - Payloads live only as long as the keys that protected them. The documentation says the API is not primarily intended for indefinitely persisted secrets, so protect tokens and cookies, not the only copy of data you must keep for years. - Payloads are not small: the format carries a header and the key id, so a short booking reference becomes a noticeably longer string.
- Is provider.CreateProtector("TravelSite").CreateProtector("BookingLinks") equivalent to provider.CreateProtector("TravelSite", "BookingLinks")?Yes. The multi-string `CreateProtector` extension simply calls `CreateProtector` once per string, each time on the protector the previous call returned. Equivalence is defined by the same strings in the same order, compared ordinally, so both chains produce protectors that can read each other's payloads. A different order would not.
- Why should a purpose chain not be built from a user name alone?The docs warn that untrusted input must not be the sole source of the chain: if a user can choose the purpose, they may pick one that collides with another component's purpose and get payloads accepted where they should not be. Put a fixed, component-specific string first and append the user-specific part after it, for example `CreateProtector("TravelSite.Messages", $"User: {userId}")`.
- IDataProtector is a good way to store user passwords.
- Any protector in the app can unprotect any payload because they share one key ring.
- Unprotect returns null when the payload has been tampered with.
- A new protector must be created for every Protect call because protectors are not thread-safe.
- Data Protection only works after you add a separate NuGet package to a web project.