您好,登錄后才能下訂單哦!
小編給大家分享一下基于ASP.NET Core數(shù)據(jù)保護(hù)如何驗(yàn)證token,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
ASP.NET Core Data Protection 不僅提供了非對(duì)稱加密能力,而且提供了靈活的秘鑰存儲(chǔ)方式以及一致的加解密接口(Protect與Unprotect)。Session中用到了它,Cookie驗(yàn)證中用到了它,OpenIdConnect中也用到了它。。。當(dāng)然你也可以在應(yīng)用開(kāi)發(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); } } }
以上是“基于ASP.NET Core數(shù)據(jù)保護(hù)如何驗(yàn)證token”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。