小編給大家分享一下基于ASP.NET Core數(shù)據(jù)保護(hù)如何驗證token,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

ASP.NET Core Data Protection 不僅提供了非對稱加密能力,而且提供了靈活的秘鑰存儲方式以及一致的加解密接口(Protect與Unprotect)。Session中用到了它,Cookie驗證中用到了它,OpenIdConnect中也用到了它。。。當(dāng)然你也可以在應(yīng)用開發(fā)中使用它,比如這篇博文中就是用它生成激活帳戶的驗證token。
首先在 Startup.ConfigureServices() 中注冊 DataProtection 服務(wù)(注入 IDataProtectionProvider 接口的實現(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ù)如何驗證token”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
網(wǎng)頁標(biāo)題:基于ASP.NETCore數(shù)據(jù)保護(hù)如何驗證token-創(chuàng)新互聯(lián)
當(dāng)前URL:http://chinadenli.net/article0/diigoo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供面包屑導(dǎo)航、網(wǎng)站營銷、外貿(mào)網(wǎng)站建設(shè)、網(wǎng)站設(shè)計、自適應(yīng)網(wǎng)站、移動網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容