Generating reset password token does not work in Azure Website
Asked Answered
W

4

60

I am implementing reset password functionality on my site by using the in-built UserManager class that comes with ASP.NET 5.

Everything works fine in my dev environment. However, once I try it in the production site that is running as an Azure website, I get the following exception:

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.

This is how I setup the UserManager instance:

var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider(SiteConfig.SiteName);
UserManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider<User>(provider.Create(ResetPasswordPurpose));

Then, I generate the token thusly (to be sent to the user in an email so that they can verify that they do indeed want to reset their password):

string token = UserManager.GeneratePasswordResetToken(user.Id);

Unfortunately, when this runs on Azure, I get the exception above.

I've Googled around and found this possible solution. However, it didn't work at all and I still get the same exception.

According to the link, it has something to do with session tokens not working on a web farm like Azure.

Wait answered 4/5, 2014 at 11:16 Comment(2)
Please vote on the issue aspnetidentity.codeplex.com/workitem/2439 to get this fixed.Rufescent
I'm getting the same error while running on an Azure VM. Is this caused by the same thing? Or should this be a new SO question?Ricker
A
92

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).

Agrobiology answered 14/5, 2014 at 18:1 Comment(7)
Reported here too. This is great feed back for asp.net team's UserVoice and Codeplex Issues Will you raise an issue?Coastal
Is that a bug? ResetPasswordPurpose should be a string right? Like "ResetPasswordPurpose"?Showcase
@yqit You can put it wherever you'd like, but It needs to be executed when the application starts. e.g. In an MVC 5 app, it should be executed by MvcApplication.Application_Start().Agrobiology
I've used this now for a long time with success, but now we added a .NET Core project. How would I need to do this now? Considering this documentation: learn.microsoft.com/en-us/aspnet/core/security/data-protection/… and this for storing in Azure Blob storage: learn.microsoft.com/en-us/aspnet/core/security/data-protection/…Creamcups
@Creamcups First off, please note that my answer is nearly 4 years old, so there's been a lot of change in APIs and the underlying platform since it was written. One of the other up-voted answers may be more helpful at this point. With that said, it looks like the only change in your situation would be in Step 2, since you want to store your machine key in Azure Blob Storage. There is a sample in the documentation that you linked to that points out how to accomplish this: docs.microsoft.com/en-us/aspnet/core/security/data-protection/…Agrobiology
Worked. I didn't need to do step 2. Best answer. Thank youSappy
you literally saved my day, thank you very much! I didn't need step 2 and I was managing to have a WIF application hosted on Plesk Obsidian 18Allard
D
47

Consider using IAppBuilder.GetDataProtectionProvider() instead of declaring a new DpapiDataProtectionProvider.

Similar to you, I had introduced this issue by configuring my UserManager like this, from a code sample I found:

public class UserManager : UserManager<ApplicationUser>
{
    public UserManager() : base(new UserStore<ApplicationUser>(new MyDbContext()))
    {
        // this does not work on azure!!!
        var provider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("ASP.NET IDENTITY");
        this.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(provider.Create("EmailConfirmation"))
        {
            TokenLifespan = TimeSpan.FromHours(24),
        };
    }
}

The CodePlex issue linked to above actually references a blog post which has been updated with a simpler solution to the problem. It recommends saving a static reference to the IDataProtector...

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

    public void ConfigureAuth(IAppBuilder app)
    {
        DataProtectionProvider = app.GetDataProtectionProvider();
        // other stuff.
    }
}

...and then referencing it from within the UserManager

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
    }
}

The answer from johnso also provides a good example of how to wire this up using Autofac.

Dichotomous answered 5/6, 2015 at 22:53 Comment(5)
Does this resolve the issue where DPAPI doesn't work in a web farm as mentioned in the top answer?Invar
No, but it allows ASP.NET Identity 2.0 to work in Azure Websites (Web Apps), which I believe is the intent of the question. The top answer has its own issues with Azure, as setting the MachineKey brings its own challenges: https://mcmap.net/q/183507/-how-to-set-machinekey-on-azure-websiteDichotomous
Thanks @Loren, works well also when you have a custom implementation of IdentityNyx
this worked for me. thank you very much @LorenPaulsen, you saved my day.Beveridge
There is indeed a difference between webfarms or VMs on Azure (where you can set/sync the machine keys) and an Azure App Service (Azure Website) where you can't set the machine key. This answer will fix the last. The other answer the former.Hellbent
T
25

I had the same issues except I was hosting on amazon ec2.
I was able to resolve it by going to the application pool in IIS and (under advanced settings after a right click) setting process model - load user profile = true.

Tardy answered 19/1, 2015 at 20:57 Comment(3)
Worked for me, too!Globin
This worked for me, thanks! I was just generating custom token outside the Account controller.Shushan
you are a heeeroooooooo. thanks alot. you saved my day.Ginoginsberg
A
12

I was having the same issue (Owin.Security.DataProtection.DpapiDataProtectionProvider failing when ran on Azure), and Staley is correct, you cannot use DpapiDataProtectionProvider.

If you're using OWIN Startup Classes you can avoid rolling your own IDataProtectionProvider, instead use the GetDataProtectionProvider method of IAppBuilder.

For instance, with Autofac:

internal static IDataProtectionProvider DataProtectionProvider;    

public void ConfigureAuth(IAppBuilder app)
{
    // ...

    DataProtectionProvider = app.GetDataProtectionProvider();

    builder.Register<IDataProtectionProvider>(c => DataProtectionProvider)
        .InstancePerLifetimeScope();

    // ...
}
Arching answered 2/6, 2015 at 1:35 Comment(3)
Thanks for keeping this answer up despite someone's downvote. It works nicely for me.Motivate
Wouldn't builder.RegisterInstance(app.GetDataProtectionProvider()); be a better choice?Scoria
Adding the WEBSITE_LOAD_USER_PROFILE to the web.config does not work, adding the setting in Azure works just fine, but requesting the DataProtectionProvider using app.GetDataProtectionProvider() is the best solution I've found. Thank you!Marinmarina

© 2022 - 2024 — McMap. All rights reserved.