ASP.NET Identity reset password
NickName:daniel Ask DateTime:2013-10-23T01:06:18

ASP.NET Identity reset password

How can I get the password of a user in the new ASP.NET Identity system? Or how can I reset without knowing the current one (user forgot password)?

Copyright Notice:Content Author:「daniel」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/19524111/asp-net-identity-reset-password

Answers
jd4u 2013-10-22T19:29:13

In current release\n\nAssuming you have handled the verification of the request to reset the forgotten password, use following code as a sample code steps.\n\nApplicationDbContext =new ApplicationDbContext()\nString userId = \"<YourLogicAssignsRequestedUserId>\";\nString newPassword = \"<PasswordAsTypedByUser>\";\nApplicationUser cUser = UserManager.FindById(userId);\nString hashedNewPassword = UserManager.PasswordHasher.HashPassword(newPassword);\nUserStore<ApplicationUser> store = new UserStore<ApplicationUser>(); \nstore.SetPasswordHashAsync(cUser, hashedNewPassword);\n\n\nIn AspNet Nightly Build\n\nThe framework is updated to work with Token for handling requests like ForgetPassword. Once in release, simple code guidance is expected.\n\nUpdate:\n\nThis update is just to provide more clear steps.\n\nApplicationDbContext context = new ApplicationDbContext();\nUserStore<ApplicationUser> store = new UserStore<ApplicationUser>(context);\nUserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(store);\nString userId = User.Identity.GetUserId();//\"<YourLogicAssignsRequestedUserId>\";\nString newPassword = \"test@123\"; //\"<PasswordAsTypedByUser>\";\nString hashedNewPassword = UserManager.PasswordHasher.HashPassword(newPassword); \nApplicationUser cUser = await store.FindByIdAsync(userId);\nawait store.SetPasswordHashAsync(cUser, hashedNewPassword);\nawait store.UpdateAsync(cUser);\n",


Shaun Luttin 2014-03-18T20:53:12

Deprecated\n\nThis was the original answer. It does work, but has a problem. What if AddPassword fails? The user is left without a password.\n\nThe original answer: we can use three lines of code:\n\nUserManager<IdentityUser> userManager = \n new UserManager<IdentityUser>(new UserStore<IdentityUser>());\n\nuserManager.RemovePassword(userId);\n\nuserManager.AddPassword(userId, newPassword);\n\n\nSee also: http://msdn.microsoft.com/en-us/library/dn457095(v=vs.111).aspx\n\nNow Recommended\n\nIt's probably better to use the answer that EdwardBrey proposed and then DanielWright later elaborated with a code sample.",


Edward Brey 2014-04-15T20:49:12

On your UserManager, first call GeneratePasswordResetTokenAsync. Once the user has verified his identity (for example by receiving the token in an email), pass the token to ResetPasswordAsync.",


Manish Vadher 2020-08-02T12:18:53

Best way to Reset Password in Asp.Net Core Identity use for Web API.\nNote* : Error() and Result() are created for internal use. You can return you want.\n [HttpPost]\n [Route("reset-password")]\n public async Task<IActionResult> ResetPassword(ResetPasswordModel model)\n {\n if (!ModelState.IsValid)\n return BadRequest(ModelState);\n try\n {\n if (model is null)\n return Error("No data found!");\n\n\n var user = await _userManager.FindByIdAsync(AppCommon.ToString(GetUserId()));\n if (user == null)\n return Error("No user found!");\n\n Microsoft.AspNetCore.Identity.SignInResult checkOldPassword =\n await _signInManager.PasswordSignInAsync(user.UserName, model.OldPassword, false, false);\n\n if (!checkOldPassword.Succeeded)\n return Error("Old password does not matched.");\n\n string resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);\n if (string.IsNullOrEmpty(resetToken))\n return Error("Error while generating reset token.");\n\n var result = await _userManager.ResetPasswordAsync(user, resetToken, model.Password);\n\n if (result.Succeeded)\n return Result();\n else\n return Error();\n }\n catch (Exception ex)\n {\n return Error(ex);\n }\n }\n",


sclarson 2013-10-22T17:48:13

string message = null;\n//reset the password\nvar result = await IdentityManager.Passwords.ResetPasswordAsync(model.Token, model.Password);\nif (result.Success)\n{\n message = \"The password has been reset.\";\n return RedirectToAction(\"PasswordResetCompleted\", new { message = message });\n}\nelse\n{\n AddErrors(result);\n}\n\n\nThis snippet of code is taken out of the AspNetIdentitySample project available on github",


Ogglas 2018-09-20T07:18:56

I think Microsoft guide for ASP.NET Identity is a good start.\n\nhttps://learn.microsoft.com/en-us/aspnet/identity/overview/features-api/account-confirmation-and-password-recovery-with-aspnet-identity\n\nNote:\n\nIf you do not use AccountController and wan't to reset your password, use Request.GetOwinContext().GetUserManager<ApplicationUserManager>();. If you dont have the same OwinContext you need to create a new DataProtectorTokenProvider like the one OwinContext uses. By default look at App_Start -> IdentityConfig.cs. Should look something like new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create(\"ASP.NET Identity\"));.\n\nCould be created like this:\n\nWithout Owin:\n\n[HttpGet]\n[AllowAnonymous]\n[Route(\"testReset\")]\npublic IHttpActionResult TestReset()\n{\n var db = new ApplicationDbContext();\n var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(db));\n var provider = new DpapiDataProtectionProvider(\"SampleAppName\");\n manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(\n provider.Create(\"SampleTokenName\"));\n\n var email = \"[email protected]\";\n\n var user = new ApplicationUser() { UserName = email, Email = email };\n\n var identityUser = manager.FindByEmail(email);\n\n if (identityUser == null)\n {\n manager.Create(user);\n identityUser = manager.FindByEmail(email);\n }\n\n var token = manager.GeneratePasswordResetToken(identityUser.Id);\n return Ok(HttpUtility.UrlEncode(token));\n}\n\n[HttpGet]\n[AllowAnonymous]\n[Route(\"testReset\")]\npublic IHttpActionResult TestReset(string token)\n{\n var db = new ApplicationDbContext();\n var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(db));\n var provider = new DpapiDataProtectionProvider(\"SampleAppName\");\n manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(\n provider.Create(\"SampleTokenName\"));\n var email = \"[email protected]\";\n var identityUser = manager.FindByEmail(email);\n var valid = Task.Run(() => manager.UserTokenProvider.ValidateAsync(\"ResetPassword\", token, manager, identityUser)).Result;\n var result = manager.ResetPassword(identityUser.Id, token, \"TestingTest1!\");\n return Ok(result);\n}\n\n\nWith Owin:\n\n[HttpGet]\n[AllowAnonymous]\n[Route(\"testResetWithOwin\")]\npublic IHttpActionResult TestResetWithOwin()\n{\n var manager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();\n\n var email = \"[email protected]\";\n\n var user = new ApplicationUser() { UserName = email, Email = email };\n\n var identityUser = manager.FindByEmail(email);\n\n if (identityUser == null)\n {\n manager.Create(user);\n identityUser = manager.FindByEmail(email);\n }\n\n var token = manager.GeneratePasswordResetToken(identityUser.Id);\n return Ok(HttpUtility.UrlEncode(token));\n}\n\n[HttpGet]\n[AllowAnonymous]\n[Route(\"testResetWithOwin\")]\npublic IHttpActionResult TestResetWithOwin(string token)\n{\n var manager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();\n\n var email = \"[email protected]\";\n var identityUser = manager.FindByEmail(email);\n var valid = Task.Run(() => manager.UserTokenProvider.ValidateAsync(\"ResetPassword\", token, manager, identityUser)).Result;\n var result = manager.ResetPassword(identityUser.Id, token, \"TestingTest1!\");\n return Ok(result);\n}\n\n\nThe DpapiDataProtectionProvider and DataProtectorTokenProvider needs to be created with the same name for a password reset to work. Using Owin for creating the password reset token and then creating a new DpapiDataProtectionProvider with another name won't work. \n\nCode that I use for ASP.NET Identity:\n\nWeb.Config:\n\n<add key=\"AllowedHosts\" value=\"example.com,example2.com\" />\n\n\nAccountController.cs:\n\n[Route(\"RequestResetPasswordToken/{email}/\")]\n[HttpGet]\n[AllowAnonymous]\npublic async Task<IHttpActionResult> GetResetPasswordToken([FromUri]string email)\n{\n if (!ModelState.IsValid)\n return BadRequest(ModelState);\n\n var user = await UserManager.FindByEmailAsync(email);\n if (user == null)\n {\n Logger.Warn(\"Password reset token requested for non existing email\");\n // Don't reveal that the user does not exist\n return NoContent();\n }\n\n //Prevent Host Header Attack -> Password Reset Poisoning. \n //If the IIS has a binding to accept connections on 80/443 the host parameter can be changed.\n //See https://security.stackexchange.com/a/170759/67046\n if (!ConfigurationManager.AppSettings[\"AllowedHosts\"].Split(',').Contains(Request.RequestUri.Host)) {\n Logger.Warn($\"Non allowed host detected for password reset {Request.RequestUri.Scheme}://{Request.Headers.Host}\");\n return BadRequest();\n }\n\n Logger.Info(\"Creating password reset token for user id {0}\", user.Id);\n\n var host = $\"{Request.RequestUri.Scheme}://{Request.Headers.Host}\";\n var token = await UserManager.GeneratePasswordResetTokenAsync(user.Id);\n var callbackUrl = $\"{host}/resetPassword/{HttpContext.Current.Server.UrlEncode(user.Email)}/{HttpContext.Current.Server.UrlEncode(token)}\";\n\n var subject = \"Client - Password reset.\";\n var body = \"<html><body>\" +\n \"<h2>Password reset</h2>\" +\n $\"<p>Hi {user.FullName}, <a href=\\\"{callbackUrl}\\\"> please click this link to reset your password </a></p>\" +\n \"</body></html>\";\n\n var message = new IdentityMessage\n {\n Body = body,\n Destination = user.Email,\n Subject = subject\n };\n\n await UserManager.EmailService.SendAsync(message);\n\n return NoContent();\n}\n\n[HttpPost]\n[Route(\"ResetPassword/\")]\n[AllowAnonymous]\npublic async Task<IHttpActionResult> ResetPasswordAsync(ResetPasswordRequestModel model)\n{\n if (!ModelState.IsValid)\n return NoContent();\n\n var user = await UserManager.FindByEmailAsync(model.Email);\n if (user == null)\n {\n Logger.Warn(\"Reset password request for non existing email\");\n return NoContent();\n } \n\n if (!await UserManager.UserTokenProvider.ValidateAsync(\"ResetPassword\", model.Token, UserManager, user))\n {\n Logger.Warn(\"Reset password requested with wrong token\");\n return NoContent();\n }\n\n var result = await UserManager.ResetPasswordAsync(user.Id, model.Token, model.NewPassword);\n\n if (result.Succeeded)\n {\n Logger.Info(\"Creating password reset token for user id {0}\", user.Id);\n\n const string subject = \"Client - Password reset success.\";\n var body = \"<html><body>\" +\n \"<h1>Your password for Client was reset</h1>\" +\n $\"<p>Hi {user.FullName}!</p>\" +\n \"<p>Your password for Client was reset. Please inform us if you did not request this change.</p>\" +\n \"</body></html>\";\n\n var message = new IdentityMessage\n {\n Body = body,\n Destination = user.Email,\n Subject = subject\n };\n\n await UserManager.EmailService.SendAsync(message);\n }\n\n return NoContent();\n}\n\npublic class ResetPasswordRequestModel\n{\n [Required]\n [Display(Name = \"Token\")]\n public string Token { get; set; }\n\n [Required]\n [Display(Name = \"Email\")]\n public string Email { get; set; }\n\n [Required]\n [StringLength(100, ErrorMessage = \"The {0} must be at least {2} characters long.\", MinimumLength = 10)]\n [DataType(DataType.Password)]\n [Display(Name = \"New password\")]\n public string NewPassword { get; set; }\n\n [DataType(DataType.Password)]\n [Display(Name = \"Confirm new password\")]\n [Compare(\"NewPassword\", ErrorMessage = \"The new password and confirmation password do not match.\")]\n public string ConfirmPassword { get; set; }\n}\n",


tmg 2015-12-02T15:18:08

Create method in UserManager<TUser, TKey>\n\npublic Task<IdentityResult> ChangePassword(int userId, string newPassword)\n{\n var user = Users.FirstOrDefault(u => u.Id == userId);\n if (user == null)\n return new Task<IdentityResult>(() => IdentityResult.Failed());\n\n var store = Store as IUserPasswordStore<User, int>;\n return base.UpdatePassword(store, user, newPassword);\n}\n",


Rahul Garg 2016-08-05T19:11:18

In case of password reset, it is recommended to reset it through sending password reset token to registered user email and ask user to provide new password. If have created a easily usable .NET library over Identity framework with default configuration settins. You can find details at blog link and source code at github.",


Daniel Wright 2015-03-24T15:23:31

\n Or how can I reset without knowing the current one (user forgot password)?\n\n\nIf you want to change a password using the UserManager but you do not want to supply the user's current password, you can generate a password reset token and then use it immediately instead.\n\nstring resetToken = await UserManager.GeneratePasswordResetTokenAsync(model.Id);\nIdentityResult passwordChangeResult = await UserManager.ResetPasswordAsync(model.Id, resetToken, model.NewPassword);\n",


More about “ASP.NET Identity reset password” related questions

ASP.NET Identity reset password

How can I get the password of a user in the new ASP.NET Identity system? Or how can I reset without knowing the current one (user forgot password)?

Show Detail

ASP.net Identity reset password without a reset token

I want to use asp.net Identity reset password without a reset token. Just enter username and new password. Is this possible? I am using webforms.

Show Detail

Webforms ASP.NET Identity system reset password

How can I get the password of a user in the new ASP.NET Identity system using webforms? Or how can I reset without knowing the current one (user forgot password)?

Show Detail

Password reset without entering email (ASP.NET Identity)

Current ASP.NET Identity password reset (through email verification) requires a user to enter e-mail and a new password to be reset. However, in most cases of a password reset, only a new password is

Show Detail

How do I implement password reset with ASP.NET Identity for ASP.NET MVC 5.0?

Microsoft is coming up with a new Membership system called ASP.NET Identity (also the default in ASP.NET MVC 5). I found the sample project, but this is not implemented a password reset. On password

Show Detail

How to reduce password reset token length in Asp.Net Identity?

I am using Asp.Net Identity for generate a password reset token. string Token = userManager.GeneratePasswordResetToken(userId); above code is giving me a token with large length. Is it possible...

Show Detail

ASP.NET Identity 2.1 - Password Reset Invalid Tokens

ASP.NET Identity is returning an 'Invalid token.' response when resetting a password for users. I've tried the following: URL Encode the code before sending email URL Encode &amp; Decode the code

Show Detail

Reset ASP.NET Identity password fails

I'm using ASP.NET MVC5 Identity and want users to be able to reset their password just by entering their email. There is only a fixed number of users and they are already set up, including an email

Show Detail

Token invalid on reset password with ASP.NET Identity

I've implemented ASP.NET Identity in my MVC application by copying the code from the VS 2013 templates. The basic thing is working, but I couldn't get the Reset Password to work. When I show the "f...

Show Detail

Token invalid on reset password with ASP.NET Identity

I've implemented ASP.NET Identity in my MVC application by copying the code from the VS 2013 templates. The basic thing is working, but I couldn't get the Reset Password to work. When I show the "f...

Show Detail