小編給大家分享一下基于ASP.NET Core數(shù)據(jù)保護如何驗證token,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
ASP.NET Core Data Protection 不僅提供了非對稱加密能力,而且提供了靈活的秘鑰存儲方式以及一致的加解密接口(Protect與Unprotect)。Session中用到了它,Cookie驗證中用到了它,OpenIdConnect中也用到了它。。。當然你也可以在應用開發(fā)中使用它,比如這篇博文中就是用它生成激活帳戶的驗證token。
首先在 Startup.ConfigureServices() 中注冊 DataProtection 服務(注入 IDataProtectionProvider 接口的實現(xiàn)):
public void ConfigureServices(IServiceCollection services) { services.AddDataProtection(); }
然后在使用 DataProtection 的類的構造函數(shù)中添加 IDataProtectionProvider 接口,并用該接口創(chuàng)建 DataProtector ,接著以此創(chuàng)建 SecureDataFormat ,最后用 SecureDataFormat.Protect() 方法生成激活帳戶的 token ,用 SecureDataFormat.Uprotect() 解密 token,完整的示例代碼如下:
public class HomeController : Controller { private readonly ISecureDataFormat_dataFormat; public HomeController(IDataProtectionProvider _dataProtectionProvider) { var dataProtector = _dataProtectionProvider.CreateProtector(typeof(HomeController).FullName); _dataFormat = new SecureDataFormat (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 { public string Deserialize(byte[] data) { return Encoding.UTF8.GetString(data); } public byte[] Serialize(string model) { return Encoding.UTF8.GetBytes(model); } } }
以上是“基于ASP.NET Core數(shù)據(jù)保護如何驗證token”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道!