简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM