Home  >  Article  >  Backend Development  >  ASP.NET Core data protection generates verification token

ASP.NET Core data protection generates verification token

高洛峰
高洛峰Original
2017-02-27 16:34:162433browse

ASP.NET Core Data Protection not only provides asymmetric encryption capabilities, 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, in this blog post, it is used to generate a verification token for activating an account.

First register the DataProtection service in Startup.ConfigureServices() (inject the implementation of the IDataProtectionProvider interface):

public void ConfigureServices(IServiceCollection services)
{
  services.AddDataProtection();
}

Then use Add the IDataProtectionProvider interface to the constructor of the DataProtection class, and use this interface to create a DataProtector, and then use it to create a SecureDataFormat. Finally, use the SecureDataFormat.Protect() method to generate a token to activate the account, and use SecureDataFormat.Uprotect() to decrypt the token. Complete sample code 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 the entire content of this article. I hope it will be helpful to everyone's learning, and I also hope that everyone will support the PHP Chinese website.

For more articles related to ASP.NET Core data protection and verification token generation, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn