首先在 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); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
更多asp.net core数据保护生成验证token。
