程序员

基于ASP.NET Core数据保护生成验证token示例

作者:admin 2021-08-02 我要评论

ASP.NET Core Data Protection 不仅提供了非对称加密能力,而且提供了灵活的秘钥存储方式以及一致的加解密接口(Protect与Unprotect)。Session中用到了它,Cook...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

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);
    }
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持站长技术。


原文链接:https://m.jb51.net/article/106545.htm

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • 十月更新修复了Windows 10的Ping of De

    十月更新修复了Windows 10的Ping of De

  • Windows10 UAC弹窗太烦但又不能关?教

    Windows10 UAC弹窗太烦但又不能关?教

  • 老大手把手教我玩 Git 变基!

    老大手把手教我玩 Git 变基!

  • 在Linux终端中展示幻灯片

    在Linux终端中展示幻灯片