Search code examples
c#asp.netentity-frameworkasp.net-mvc-5asp.net-identity-2

How do I reset a user's password in EntityFramework Seed() method?


I want to reset the administrator's password in the Seed method of EntityFramework. However, because there is no OWIN context, I cannot initalize ApplicationUserManager to generate a token.

This is my code:

protected override void Seed(ModelUNRegister.Models.ApplicationDbContext context)

var userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(context));
// How should I Initalize userManager.UserTokenProvider?

if (userManager.FindByName(AppSettings.InitalAdminAccount) == null)
{
    // Create user
}
else
{
    var adminUser = userManager.FindByName(AppSettings.InitalAdminAccount);
    // The following code throws error: IUserTokenProvider is not registered.
    string resetToken = userManager.GeneratePasswordResetToken(adminUser.Id);
    var result = userManager.ResetPassword(adminUser.Id, resetToken, AppSettings.InitalAdminPassword);

    if (!result.Succeeded) throw new InvalidOperationException(string.Concat(result.Errors));
}

I would like to know if there is other ways to generate a token to change the password.


Solution

  • You do not need OWIN context, in your code you instantiated a UserManager. You have to show your UserManager code if you want suggestions about IUserTokenProvider But you can update the password without generating tokens. Add method to UserManager

    public Task<IdentityResult> ChangePassword(ApplicationUser user, string newPassword)
    {
         var store = Store as IUserPasswordStore<ApplicationUser, string>;
         return UpdatePassword(store, user, newPassword);
    }
    

    and in your Seed

    userManager.ChangePassword(adminUser, AppSettings.InitalAdminPassword);