[ASP.NET Identity] 問題篇 - 出現 CryptographicException 解法

最近將ASP.NET Identity導入專案內 ,ResetPassword功能上測試機時
出現 System.Security.Cryptography.CryptographicException 的錯誤
就來記錄一下解決過程

問題點

 var token = await _userManager.GeneratePasswordResetTokenAsync(model.Id);
 var result = await _userManager.ResetPasswordAsync(model.Id, token, model.Password);

上面是ResetPassword code 這段code 在本機上開發時 都正常
但是上測試機 會就出現

System.Security.Cryptography.CryptographicException: The data protection operation was unsuccessful. This may have been caused by not having the user profile loaded for the current thread's user context, which may be the case when the thread is impersonating.

解法

1.是自己管理的IIS
可以到 應用程式集區 -> 進階設定 -> 處理序模型 -> 載入使用者設定檔 改成 True
參考網址
https://mlichtenberg.wordpress.com/2016/01/08/generatepasswordresettokenasync-and-data-protection-operation-errors/

2.不是自己管的IIS
就要自己寫程式碼了 不過我沒有實作 大致上就是要自己生成 DataProtectionProvider

public partial class Startup
{
    internal static IDataProtectionProvider DataProtectionProvider { get; private set; }

    public void ConfigureAuth(IAppBuilder app)
    {
        DataProtectionProvider = app.GetDataProtectionProvider();
        // other stuff.
    }
}
public class UserManager : UserManager<ApplicationUser>
{
    public UserManager() : base(new UserStore<ApplicationUser>(new MyDbContext()))
    {
        var dataProtectionProvider = Startup.DataProtectionProvider;
        this.UserTokenProvider = 
                new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));

        // do other configuration
    }
}

以上程式碼 是來自 
ASP.NET Identity and CryptographicException when running your site on Microsoft Azure Web-Sites

結語

ASP.NET Identity 還蠻方便的 

如果內容有誤請多鞭策謝謝