基于ASP.NET Core数据保护生成验证token示例
ASP.NETCoreDataProtection不仅提供了非对称加密能力,而且提供了灵活的秘钥存储方式以及一致的加解密接口(Protect与Unprotect)。Session中用到了它,Cookie验证中用到了它,OpenIdConnect中也用到了它。。。当然你也可以在应用开发中使用它,比如这篇博文中就是用它生成激活帐户的验证token。
首先在Startup.ConfigureServices()中注册DataProtection服务(注入IDataProtectionProvider接口的实现):
publicvoidConfigureServices(IServiceCollectionservices)
{
services.AddDataProtection();
}
然后在使用DataProtection的类的构造函数中添加IDataProtectionProvider接口,并用该接口创建DataProtector,接着以此创建SecureDataFormat,最后用SecureDataFormat.Protect()方法生成激活帐户的token,用SecureDataFormat.Uprotect()解密token,完整的示例代码如下:
publicclassHomeController:Controller
{
privatereadonlyISecureDataFormat<string>_dataFormat;
publicHomeController(IDataProtectionProvider_dataProtectionProvider)
{
vardataProtector=_dataProtectionProvider.CreateProtector(typeof(HomeController).FullName);
_dataFormat=newSecureDataFormat<string>(newStringSerializer(),dataProtector);
}
publicstringGenerateToken()
{
return_dataFormat.Protect(Guid.NewGuid().ToString()+";"+DateTime.Now.AddHours(10));
}
publicstringDecryptToken(stringtoken)
{
return_dataFormat.Unprotect(token);
}
privateclassStringSerializer:IDataSerializer<string>
{
publicstringDeserialize(byte[]data)
{
returnEncoding.UTF8.GetString(data);
}
publicbyte[]Serialize(stringmodel)
{
returnEncoding.UTF8.GetBytes(model);
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。