Example of token Generation and Verification Based on ASP. NET Core data protection, coretoken
ASP. NET Core Data Protection not only provides asymmetric encryption, but also provides flexible key storage methods and consistent encryption and decryption interfaces (Protect and Unprotect ). It is used in Session, Cookie verification, and OpenIdConnect... Of course, you can also use it in application development. For example, this blog post uses it to generate verification tokens for activation accounts.
First, register the DataProtection service in Startup. ConfigureServices () (to inject the IDataProtectionProvider Interface ):
public void ConfigureServices(IServiceCollection services){ services.AddDataProtection();}
Then, add the IDataProtectionProvider interface to the constructor of the DataProtection class, use this interface to create DataProtector, then create SecureDataFormat, and finally use SecureDataFormat. the Protect () method generates the token for activating the account, and uses SecureDataFormat. uprotect () decrypts the token. The complete sample code is as follows:
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); } }}
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.