ASP.NET Core 'de veri koruma API 'Lerini kullanmaya başlayın
Temel olarak, verileri korumak aşağıdaki adımlardan oluşur:
- Bir veri koruma sağlayıcısından veri koruyucusu oluşturun.
- Korumak istediğiniz
Protectverilerle yöntemi çağırın. UnprotectDüz metin haline döndürmek istediğiniz verilerle yöntemi çağırın.
ASP.NET Core veya gibi birçok çerçeve ve uygulama modeli, SignalR veri koruma sistemini zaten yapılandırıp bağımlılık eklemeyoluyla erişilen bir hizmet kapsayıcısına ekler. Aşağıdaki örnek şunları göstermektedir:
- Bağımlılık ekleme ve veri koruma yığınını kaydetme için bir hizmet kapsayıcısı yapılandırma.
- Veri koruma sağlayıcısı dı aracılığıyla alınıyor.
- Bir koruyucu oluşturuluyor.
- Verilerin korunmasını geri alınıyor.
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!
*/
Bir koruyucu oluşturduğunuzda bir veya daha fazla Amaç dizesisağlamanız gerekir. Amaç dizesi, tüketiciler arasında yalıtım sağlar. Örneğin, "yeşil" bir amaç dizesiyle oluşturulan bir koruyucu, "mor" amacını taşıyan bir koruyucu tarafından belirtilen verilerin korumasını yapamaz.
İpucu
Ve örnekleri IDataProtectionProvider , IDataProtector birden çok çağıranlar için iş parçacığı güvenlidir. Bir bileşen bir öğesine çağrısıyla öğesine bir başvuru aldıktan sonra IDataProtector CreateProtector , ve ' a yönelik birden çok çağrı için bu başvuruyu kullanacaktır Protect Unprotect .
UnprotectKorumalı yük doğrulanamazsa veya çözümlenememişse, öğesine yapılan bir çağrı CryptographicException oluşturur. Bazı bileşenler, kaldırma işlemleri sırasında hataları yoksaymak isteyebilir; kimlik doğrulamasını okuyan bir bileşen cookie Bu hatayı işleyebilir ve isteği cookie , isteğin hemen başarısız olması yerine hiç olmadığı gibi ele alabilir. Bu davranışın, tüm özel durumlara izin vermek yerine CryptographicException özel olarak yakalamalı bileşenler.
Özel depoyu yapılandırmak için Addoseçenekleri kullanma
Uygulamasının bir tek bir hizmete bağımlılığı olduğundan, hizmet sağlayıcısı kullanan aşağıdaki kodu göz önünde bulundurun IXmlRepository :
public void ConfigureServices(IServiceCollection services)
{
// ...
var sp = services.BuildServiceProvider();
services.AddDataProtection()
.AddKeyManagementOptions(o => o.XmlRepository = sp.GetService<IXmlRepository>());
}
Yukarıdaki kod şu uyarıyı günlüğe kaydeder:
Uygulama kodundan ' BuildServiceProvider ' çağrısı, oluşturulan Singleton hizmetlerinin ek bir kopyasına neden olur. Bağımlılık ekleme hizmetleri gibi alternatifleri, ' configure ' için parametre olarak düşünün.
Aşağıdaki kod, IXmlRepository hizmet sağlayıcısı oluşturmaya gerek kalmadan uygulamayı sağlar ve bu nedenle Singleton hizmetlerinin ek kopyalarını yapar:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataProtectionDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
// Register XmlRepository for data protection.
services.AddOptions<KeyManagementOptions>()
.Configure<IServiceScopeFactory>((options, factory) =>
{
options.XmlRepository = new CustomXmlRepository(factory);
});
services.AddRazorPages();
}
Yukarıdaki kod, ' a çağrıyı kaldırır GetService ve gizler IConfigureOptions<T> .
Aşağıdaki kod özel XML deposunu gösterir:
using CustomXMLrepo.Data;
using Microsoft.AspNetCore.DataProtection.Repositories;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
public class CustomXmlRepository : IXmlRepository
{
private readonly IServiceScopeFactory factory;
public CustomXmlRepository(IServiceScopeFactory factory)
{
this.factory = factory;
}
public IReadOnlyCollection<XElement> GetAllElements()
{
using (var scope = factory.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<DataProtectionDbContext>();
var keys = context.XmlKeys.ToList()
.Select(x => XElement.Parse(x.Xml))
.ToList();
return keys;
}
}
public void StoreElement(XElement element, string friendlyName)
{
var key = new XmlKey
{
Xml = element.ToString(SaveOptions.DisableFormatting)
};
using (var scope = factory.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<DataProtectionDbContext>();
context.XmlKeys.Add(key);
context.SaveChanges();
}
}
}
Aşağıdaki kod XmlKey sınıfını göstermektedir:
public class XmlKey
{
public Guid Id { get; set; }
public string Xml { get; set; }
public XmlKey()
{
this.Id = Guid.NewGuid();
}
}