如何使用ASP.NET MVC 5的UserManager重置密码

时间:2014-03-19 19:59:03

标签: c# passwords asp.net-mvc-5 reset-password usermanager

我想知道是否有办法使用 ASP.NET MVC 5的<{1}}重置密码

我尝试使用已有密码但没有成功的用户。任何线索?

UserManager

7 个答案:

答案 0 :(得分:85)

这是ASP.NET Identity reset password

UserManager<IdentityUser> userManager = 
    new UserManager<IdentityUser>(new UserStore<IdentityUser>());

userManager.RemovePassword(userId);

userManager.AddPassword(userId, newPassword);

答案 1 :(得分:29)

我认为这是更新的,但在Identity 2.0中有这样的API:

IdentityResult result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);

model.Code按以下方式生成,您应该将其作为电子邮件中的链接发送,以确保声称要更改密码的用户是拥有该电子邮件地址的用户:

string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

答案 2 :(得分:4)

尝试使用用户商店:

 var user = UserManager.FindById(forgotPasswordEvent.UserId);

 UserStore<ApplicationUser> store = new UserStore<ApplicationUser>();
 store.SetPasswordHashAsync(user, uManager.PasswordHasher.HashPassword(model.ConfirmPassword));

IdentityMembership很酷,但仍然是lacking some implementation

<强>更新

Identity 2.0现已上市,功能更多

答案 3 :(得分:4)

var validPass= await userManager.PasswordValidator.ValidateAsync(txtPassword1.Text);
if(validPass.Succeeded)
{
    var user = userManager.FindByName(currentUser.LoginName);
    user.PasswordHash = userManager.PasswordHasher.HashPassword(txtPassword1.Text);
    var res= userManager.Update(user);
    if(res.Succeeded)
    {
        // change password has been succeeded
    }
}

答案 4 :(得分:3)

我将此添加到我的UserManager类:

    public virtual async Task<IdentityResult> UpdatePassword(ApplicationUser user, string newPassword)
    {
        var passwordStore = Store as IUserPasswordStore<ApplicationUser, string>;

        if (passwordStore == null)
            throw new Exception("UserManager store does not implement IUserPasswordStore");

        var result = await base.UpdatePassword(passwordStore, user, newPassword);

        if (result.Succeeded)
            result = await base.UpdateAsync(user);

        return result;
    }

答案 5 :(得分:3)

试试这段代码。它运作得很完美:

    var userStore = new UserStore<IdentityUser>();

    var userManager = new UserManager<IdentityUser>(userStore);

    string userName= UserName.Text;

    var user =userManager.FindByName(userName);
    if (user.PasswordHash != null  )
    {
        userManager.RemovePassword(user.Id);
    }

    userManager.AddPassword(user.Id, newpassword);

答案 6 :(得分:2)

在名称空间Microsoft.AspNet.Identity中有更改密码的扩展名。

https://msdn.microsoft.com/en-us/library/dn497466(v=vs.108).aspx