Generating reset password token does not work in Azure Website

The DpapiDataProtectionProvider utilizes DPAPI which will not work properly in a web farm/cloud environment since encrypted data can only be decrypted by the machine that encypted it. What you need is a way to encrypt data such that it can be decrypted by any machine in your environment. Unfortunately, ASP.NET Identity 2.0 does not include any other implementation of IProtectionProvider other than DpapiDataProtectionProvider. However, it’s not too difficult to roll your own.

One option is to utilize the MachineKey class as follows:

public class MachineKeyProtectionProvider : IDataProtectionProvider
{
    public IDataProtector Create(params string[] purposes)
    {
        return new MachineKeyDataProtector(purposes);
    }
}

public class MachineKeyDataProtector : IDataProtector
{
    private readonly string[] _purposes;

    public MachineKeyDataProtector(string[] purposes)
    {
        _purposes = purposes;
    }

    public byte[] Protect(byte[] userData)
    {
        return MachineKey.Protect(userData, _purposes);
    }

    public byte[] Unprotect(byte[] protectedData)
    {
        return MachineKey.Unprotect(protectedData, _purposes);
    }
}

In order to use this option, there are a couple of steps that you would need to follow.

Step 1

Modify your code to use the MachineKeyProtectionProvider.

using Microsoft.AspNet.Identity.Owin;
// ...

var provider = new MachineKeyProtectionProvider();
UserManager.UserTokenProvider = new DataProtectorTokenProvider<User>(
    provider.Create("ResetPasswordPurpose"));

Step 2

Synchronize the MachineKey value across all the machines in your web farm/cloud environment. This sounds scary, but it’s the same step that we’ve performed countless times before in order to get ViewState validation to work properly in a web farm (it also uses DPAPI).

Leave a Comment