Omówienie interfejsów API odbiorców dla ASP.NET CoreConsumer APIs overview for ASP.NET Core
IDataProtectionProvider
Interfejsy i IDataProtector
to podstawowe interfejsy, za pomocą których konsumenci używają systemu ochrony danych.The IDataProtectionProvider
and IDataProtector
interfaces are the basic interfaces through which consumers use the data protection system. Znajdują się one w pakiecie Microsoft. AspNetCore. dataprotection. Abstracts .They're located in the Microsoft.AspNetCore.DataProtection.Abstractions package.
IDataProtectionProviderIDataProtectionProvider
Interfejs dostawcy reprezentuje główny system ochrony danych.The provider interface represents the root of the data protection system. Nie może być on bezpośrednio używany do ochrony lub wyochronowania danych.It cannot directly be used to protect or unprotect data. Zamiast tego konsument musi uzyskać odwołanie do obiektu IDataProtector
przez wywołanie IDataProtectionProvider.CreateProtector(purpose)
, gdzie cel jest ciągiem opisującym zamierzony przypadek użycia konsumenta.Instead, the consumer must get a reference to an IDataProtector
by calling IDataProtectionProvider.CreateProtector(purpose)
, where purpose is a string that describes the intended consumer use case. Zobacz ciągi przeznaczenia , aby uzyskać więcej informacji na temat zamiaru tego parametru i sposobu wybierania odpowiedniej wartości.See Purpose Strings for much more information on the intent of this parameter and how to choose an appropriate value.
IDataProtectorIDataProtector
Interfejs funkcji ochrony jest zwracany przez wywołanie do CreateProtector
i jest to interfejs, którego klienci mogą używać do wykonywania operacji ochrony i wycofania ochrony.The protector interface is returned by a call to CreateProtector
, and it's this interface which consumers can use to perform protect and unprotect operations.
Aby chronić dane, Przekaż dane do Protect
metody.To protect a piece of data, pass the data to the Protect
method. Basic Interface definiuje metodę, która konwertuje bajt []-> Byte [], ale istnieje również Przeciążenie (dostarczone jako Metoda rozszerzenia), które konwertuje ciąg > ciągu.The basic interface defines a method which converts byte[] -> byte[], but there's also an overload (provided as an extension method) which converts string -> string. Zabezpieczenia oferowane przez dwie metody są identyczne. Deweloper powinien wybrać dowolne Przeciążenie, które jest najwygodniejsze dla przypadków użycia.The security offered by the two methods is identical; the developer should choose whichever overload is most convenient for their use case. Niezależnie od wybranego przeciążenia, wartość zwrócona przez metodę ochrony jest teraz chroniona (ENCIPHERED i nieautoryzowane), a aplikacja może wysłać ją do niezaufanego klienta.Irrespective of the overload chosen, the value returned by the Protect method is now protected (enciphered and tamper-proofed), and the application can send it to an untrusted client.
Aby wyłączyć ochronę wcześniej chronionego fragmentu danych, Przekaż chronione dane do Unprotect
metody.To unprotect a previously-protected piece of data, pass the protected data to the Unprotect
method. (Istnieją oparte na bajtach [] i przeciążenia oparte na ciągach dla wygody dla deweloperów). Jeśli chroniony ładunek został wygenerowany przez wcześniejsze wywołanie do Protect
tego samego IDataProtector
, Unprotect
Metoda zwróci oryginalny niechroniony ładunek.(There are byte[]-based and string-based overloads for developer convenience.) If the protected payload was generated by an earlier call to Protect
on this same IDataProtector
, the Unprotect
method will return the original unprotected payload. Jeśli chroniony ładunek został naruszony lub został wyprodukowany przez inny IDataProtector
, Unprotect
Metoda zwróci CryptographicException.If the protected payload has been tampered with or was produced by a different IDataProtector
, the Unprotect
method will throw CryptographicException.
Koncepcja tego samego programu a różne IDataProtector
powiązania z powrotem do koncepcji celu.The concept of same vs. different IDataProtector
ties back to the concept of purpose. Jeśli dwa IDataProtector
wystąpienia zostały wygenerowane z tego samego katalogu głównego IDataProtectionProvider
, ale za pośrednictwem różnych ciągów przeznaczenie w wywołaniu IDataProtectionProvider.CreateProtector
, są one uznawane za różne funkcje ochrony, a nikt nie będzie w stanie chronić ładunków wygenerowanych przez inne.If two IDataProtector
instances were generated from the same root IDataProtectionProvider
but via different purpose strings in the call to IDataProtectionProvider.CreateProtector
, then they're considered different protectors, and one won't be able to unprotect payloads generated by the other.
Korzystanie z tych interfejsówConsuming these interfaces
W przypadku składnika o podwójnej próbie zamierzone użycie polega na tym, że składnik przyjmuje IDataProtectionProvider
parametr w konstruktorze, a system di automatycznie udostępnia tę usługę podczas tworzenia wystąpienia składnika.For a DI-aware component, the intended usage is that the component takes an IDataProtectionProvider
parameter in its constructor and that the DI system automatically provides this service when the component is instantiated.
Uwaga
Niektóre aplikacje (takie jak aplikacje konsolowe lub aplikacje ASP.NET 4. x) mogą nie być rozróżniane, więc nie można użyć mechanizmu opisanego w tym miejscu.Some applications (such as console applications or ASP.NET 4.x applications) might not be DI-aware so cannot use the mechanism described here. W tych scenariuszach zapoznaj się z dokumentem scenariusze bez nieznanej wiedzy , aby uzyskać więcej informacji na temat uzyskiwania wystąpienia IDataProtection
dostawcy bez przechodzenia przez di.For these scenarios consult the Non DI Aware Scenarios document for more information on getting an instance of an IDataProtection
provider without going through DI.
Poniższy przykład ilustruje trzy koncepcje:The following sample demonstrates three concepts:
Dodaj system ochrony danych do kontenera usługi,Add the data protection system to the service container,
Przy użyciu DI, aby otrzymać wystąpienie elementu
IDataProtectionProvider
, iUsing DI to receive an instance of anIDataProtectionProvider
, andTworzenie
IDataProtector
z poziomuIDataProtectionProvider
i używanie go do ochrony i nieochrony danych.Creating anIDataProtector
from anIDataProtectionProvider
and using it to protect and unprotect data.
using System;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.DependencyInjection;
public class Program
{
public static void Main(string[] args)
{
// add data protection services
var serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection();
var services = serviceCollection.BuildServiceProvider();
// create an instance of MyClass using the service provider
var instance = ActivatorUtilities.CreateInstance<MyClass>(services);
instance.RunSample();
}
public class MyClass
{
IDataProtector _protector;
// the 'provider' parameter is provided by DI
public MyClass(IDataProtectionProvider provider)
{
_protector = provider.CreateProtector("Contoso.MyClass.v1");
}
public void RunSample()
{
Console.Write("Enter input: ");
string input = Console.ReadLine();
// protect the payload
string protectedPayload = _protector.Protect(input);
Console.WriteLine($"Protect returned: {protectedPayload}");
// unprotect the payload
string unprotectedPayload = _protector.Unprotect(protectedPayload);
Console.WriteLine($"Unprotect returned: {unprotectedPayload}");
}
}
}
/*
* SAMPLE OUTPUT
*
* Enter input: Hello world!
* Protect returned: CfDJ8ICcgQwZZhlAlTZT...OdfH66i1PnGmpCR5e441xQ
* Unprotect returned: Hello world!
*/
Pakiet Microsoft. AspNetCore. dataprotection. Abstracts zawiera metodę rozszerzenia IServiceProvider.GetDataProtector
jako wygodę dla deweloperów.The package Microsoft.AspNetCore.DataProtection.Abstractions contains an extension method IServiceProvider.GetDataProtector
as a developer convenience. Jest on hermetyzowany jako pojedyncza operacja zarówno pobierającą IDataProtectionProvider
od dostawcy usługi, jak i wywołującym IDataProtectionProvider.CreateProtector
.It encapsulates as a single operation both retrieving an IDataProtectionProvider
from the service provider and calling IDataProtectionProvider.CreateProtector
. Poniższy przykład demonstruje użycie.The following sample demonstrates its usage.
using System;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.DependencyInjection;
public class Program
{
public static void Main(string[] args)
{
// add data protection services
var serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection();
var services = serviceCollection.BuildServiceProvider();
// get an IDataProtector from the IServiceProvider
var protector = services.GetDataProtector("Contoso.Example.v2");
Console.Write("Enter input: ");
string input = Console.ReadLine();
// protect the payload
string protectedPayload = protector.Protect(input);
Console.WriteLine($"Protect returned: {protectedPayload}");
// unprotect the payload
string unprotectedPayload = protector.Unprotect(protectedPayload);
Console.WriteLine($"Unprotect returned: {unprotectedPayload}");
}
}
Porada
Wystąpienia IDataProtectionProvider
i IDataProtector
są bezpieczne dla wątków dla wielu wywołań.Instances of IDataProtectionProvider
and IDataProtector
are thread-safe for multiple callers. Jest to zamierzone, gdy składnik pobiera odwołanie do elementu IDataProtector
za pośrednictwem wywołania do CreateProtector
, będzie używać tego odwołania dla wielu wywołań do Protect
i Unprotect
.It's intended that once a component gets a reference to an IDataProtector
via a call to CreateProtector
, it will use that reference for multiple calls to Protect
and Unprotect
. Wywołanie będzie zgłaszać Unprotect
CryptographicException, jeśli nie można zweryfikować ani deszyfrowanie chronionego ładunku.A call to Unprotect
will throw CryptographicException if the protected payload cannot be verified or deciphered. Niektóre składniki mogą chcieć zignorować błędy podczas operacji usunięcia ochrony; składnik, który odczytuje uwierzytelnianie cookie s, może obsłużyć ten błąd i traktować żądanie tak, jakby nie było cookie w ogóle kończyć się niepowodzeniem.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. Składniki, które chcą tego zachowania, powinny zwrócić uwagę na CryptographicException zamiast połknięcia wszystkich wyjątków.Components which want this behavior should specifically catch CryptographicException instead of swallowing all exceptions.