How to reset password with UserManager of ASP.NET MVC 5
我想知道是否有一种方法可以使用ASP.NET MVC 5的
我用已经有密码但没有成功的用户尝试过此操作。有任何线索吗?
1 2 3 4 5 6 7 8 9 | IdentityResult result = UserManager.AddPassword(forgotPasswordEvent.UserId.ToString(), model.ConfirmPassword); if (result.Succeeded) { // } else { AddErrors(result); } |
这里是ASP.NET身份重置密码
1 2 3 4 5 6 |
我想这是较新的,但是Identity 2.0中有这样的API:
1 | IdentityResult result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password); |
model.Code是通过以下方式生成的,您应该将此链接作为电子邮件中的链接发送,以确保声称要更改密码的用户是拥有该电子邮件地址的用户:
1 | string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); |
1 2 3 4 5 6 7 8 9 10 11 | 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 } } |
尝试使用用户存储:
1 2 3 4 | var user = UserManager.FindById(forgotPasswordEvent.UserId); UserStore<ApplicationUser> store = new UserStore<ApplicationUser>(); store.SetPasswordHashAsync(user, uManager.PasswordHasher.HashPassword(model.ConfirmPassword)); |
IdentityMembership很酷,但是仍然缺乏实现
更新
Identity 2.0现已发布,并具有更多功能
尝试以下代码。它运行良好:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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); |
我将此添加到了UserManager类中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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; } |
有扩展名可以更改名称空间Microsoft.AspNet.Identity中的密码。
https://msdn.microsoft.com/zh-cn/library/dn497466(v = vs.108).aspx