zoukankan      html  css  js  c++  java
  • 基于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);
            }
        }
    }
  • 相关阅读:
    Linux 使用 github 常用命令
    配置使用 git 秘钥连接 GitHub
    Python 使用 face_recognition 人脸识别
    face_recognition 基础接口
    pycharm 安装激活操作
    Python 人工智能之人脸识别 face_recognition 模块安装
    Linux pip 命令无法使用问题
    vue 起步
    vue.JS 介绍
    AngularJS 简介
  • 原文地址:https://www.cnblogs.com/dudu/p/6395021.html
Copyright © 2011-2022 走看看