2.4 KiB
title | author | description | ms.author | manager | ms.date | ms.topic | ms.technology | ms.prod | uid |
---|---|---|---|---|---|---|---|---|---|
Getting Started with the Data Protection APIs | rick-anderson | This document explains how to use the ASP.NET Core data protection APIs for protecting and unprotecting data in an app. | riande | wpickett | 10/14/2016 | article | aspnet | asp.net-core | security/data-protection/using-data-protection |
Getting Started with the Data Protection APIs
At its simplest, protecting data consists of the following steps:
-
Create a data protector from a data protection provider.
-
Call the
Protect
method with the data you want to protect. -
Call the
Unprotect
method with the data you want to turn back into plain text.
Most frameworks and app models, such as ASP.NET or SignalR, already configure the data protection system and add it to a service container you access via dependency injection. The following sample demonstrates configuring a service container for dependency injection and registering the data protection stack, receiving the data protection provider via DI, creating a protector and protecting then unprotecting data
[!code-csharpMain]
When you create a protector you must provide one or more Purpose Strings. A purpose string provides isolation between consumers. For example, a protector created with a purpose string of "green" wouldn't be able to unprotect data provided by a protector with a purpose of "purple".
[!TIP] Instances of
IDataProtectionProvider
andIDataProtector
are thread-safe for multiple callers. It's intended that once a component gets a reference to anIDataProtector
via a call toCreateProtector
, it will use that reference for multiple calls toProtect
andUnprotect
.A call to
Unprotect
will throw CryptographicException if the protected payload cannot be verified or deciphered. Some components may wish to ignore errors during unprotect operations; a component which reads authentication cookies might handle this error and treat the request as if it had no cookie at all rather than fail the request outright. Components which want this behavior should specifically catch CryptographicException instead of swallowing all exceptions.