基於ASP.NET Core Data Protection生成驗證token


ASP.NET Core Data Protection 不僅提供了非對稱加密能力,而且提供了靈活的秘鑰存儲方式以及一致的加解密接口(Protect與Unprotect)。Session中用到了它,Cookie驗證中用到了它,OpenIdConnect中也用到了它。。。當然你也可以在應用開發中使用它,比如這篇博文中就是用它生成激活帳戶的驗證token。

首先在 Startup.ConfigureServices() 中注冊 DataProtection 服務(注入 IDataProtectionProvider 接口的實現):

public void ConfigureServices(IServiceCollection services)
{
    services.AddDataProtection();
}

然后在使用 DataProtection 的類的構造函數中添加 IDataProtectionProvider 接口,並用該接口創建 DataProtector ,接着以此創建 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);
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM