Generate validation token sample based on ASP. NET Core data protection

  • 2021-09-12 00:53:39
  • OfStack

ASP. NET Core Data Protection not only provides asymmetric encryption capability, but also provides flexible secret key storage mode and encryption and decryption interfaces (Protect and Unprotect). It's used in Session, Cookie validation, and OpenIdConnect. . . Of course, you can also use it in application development, for example, in this blog post, it is used to generate the authentication token of activation account.

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


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

Then add the IDataProtectionProvider interface to the constructor of the class that uses DataProtection, and use this interface to create DataProtector, then use this to create SecureDataFormat, and finally use the SecureDataFormat. Protect () method to generate token to activate the account, and use SecureDataFormat. Uprotect () to decrypt 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);
    }
  }
}


Related articles: