ASP.NET Core Data Protection 不僅提供了非對(duì)稱加密能力,而且提供了靈活的秘鑰存儲(chǔ)方式以及一致的加解密接口(Protect與Unprotect)。Session中用到了它,Cookie驗(yàn)證中用到了它,OpenIdConnect中也用到了它。。。當(dāng)然你也可以在應(yīng)用開發(fā)中使用它,比如這篇博文中就是用它生成激活帳戶的驗(yàn)證token。
首先在 Startup.ConfigureServices() 中注冊(cè) DataProtection 服務(wù)(注入 IDataProtectionProvider 接口的實(shí)現(xiàn)):
public void ConfigureServices(IServiceCollection services){ services.AddDataProtection();}然后在使用 DataProtection 的類的構(gòu)造函數(shù)中添加 IDataProtectionProvider 接口,并用該接口創(chuàng)建 DataProtector ,接著以此創(chuàng)建 SecureDataFormat ,最后用 SecureDataFormat.Protect() 方法生成激活帳戶的 token ,用 SecureDataFormat.Uprotect() 解密 token,完整的示例代碼如下:
public class HomeController : Controller{ private readonly ISecureDataFormat<string> _dataFormat; public HomeController(IDataProtectionProvider _dataProtectionProvider) { var dataProtector = _dataProtectionProvider.CreateProtector(typeof(HomeController).FullName); _dataFormat = new SecureDataFormat<string>(new StringSerializer(), dataProtector); } public string GenerateToken() { return _dataFormat.Protect(Guid.NewGuid().ToString() + ";" + DateTime.Now.AddHours(10)); } public string DecryptToken(string token) { return _dataFormat.Unprotect(token); } private class StringSerializer : IDataSerializer<string> { public string Deserialize(byte[] data) { return Encoding.UTF8.GetString(data); } public byte[] Serialize(string model) { return Encoding.UTF8.GetBytes(model); } }}以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持錯(cuò)新站長(zhǎng)站。
新聞熱點(diǎn)
疑難解答
圖片精選