ASP.NET身份重置密码

如何在新的ASP.NET身份系统中获取用户的密码? 或者我怎么能不知道当前(用户忘记密码)重置?

在当前版本中

假设您已经处理了重置忘记密码的请求validation,请使用以下代码作为示例代码步骤。

ApplicationDbContext =new ApplicationDbContext() String userId = "<YourLogicAssignsRequestedUserId>"; String newPassword = "<PasswordAsTypedByUser>"; ApplicationUser cUser = UserManager.FindById(userId); String hashedNewPassword = UserManager.PasswordHasher.HashPassword(newPassword); UserStore<ApplicationUser> store = new UserStore<ApplicationUser>(); store.SetPasswordHashAsync(cUser, hashedNewPassword); 

在AspNet每晚生成

该框架更新为与Token一起处理像ForgetPassword这样的请求。 一旦发布,预计会有简单的代码指导。

更新:

此更新只是为了提供更清晰的步骤。

 ApplicationDbContext context = new ApplicationDbContext(); UserStore<ApplicationUser> store = new UserStore<ApplicationUser>(context); UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(store); String userId = User.Identity.GetUserId();//"<YourLogicAssignsRequestedUserId>"; String newPassword = "test@123"; //"<PasswordAsTypedByUser>"; String hashedNewPassword = UserManager.PasswordHasher.HashPassword(newPassword); ApplicationUser cUser = await store.FindByIdAsync(userId); await store.SetPasswordHashAsync(cUser, hashedNewPassword); await store.UpdateAsync(cUser); 

或者我怎么能不知道当前(用户忘记密码)重置?

如果要使用UserManager更改密码,但不想提供用户的当前密码,则可以生成密码重置令牌,然后立即使用它。

 string resetToken = await UserManager.GeneratePasswordResetTokenAsync(model.Id); IdentityResult passwordChangeResult = await UserManager.ResetPasswordAsync(model.Id, resetToken, model.NewPassword); 

弃用

这是原来的答案。 它确实有用,但是有一个问题。 如果AddPassword失败怎么办? 用户没有密码。

原来的答案:我们可以使用三行代码:

 UserManager<IdentityUser> userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>()); userManager.RemovePassword(userId); userManager.AddPassword(userId, newPassword); 

另请参阅: http : //msdn.microsoft.com/zh-cn/library/dn457095(v=vs.111).aspx

现在推荐

用EdwardBrey提出的答案,然后DanielWright后来用一个代码样本进行阐述可能会更好。

在你的UserManager ,首先调用GeneratePasswordResetTokenAsync 。 一旦用户validation了他的身份(例如通过在电子邮件中接收令牌),将令牌传递给ResetPasswordAsync 。

UserManager<TUser, TKey>创build方法UserManager<TUser, TKey>

 public Task<IdentityResult> ChangePassword(int userId, string newPassword) { var user = Users.FirstOrDefault(u => u.Id == userId); if (user == null) return new Task<IdentityResult>(() => IdentityResult.Failed()); var store = Store as IUserPasswordStore<User, int>; return base.UpdatePassword(store, user, newPassword); } 
 string message = null; //reset the password var result = await IdentityManager.Passwords.ResetPasswordAsync(model.Token, model.Password); if (result.Success) { message = "The password has been reset."; return RedirectToAction("PasswordResetCompleted", new { message = message }); } else { AddErrors(result); } 

这段代码从github上提供的AspNetIdentitySample项目中取出

在密码重置的情况下,build议通过将密码重置令牌发送给注册用户电子邮件进行重置,并要求用户提供新密码。 如果已经使用默认configuration设置创build了一个通过Identity框架轻松使用的.NET库。 您可以在github的博客链接和源代码中find详细信息。