I have an application which uses ASP.net Identity as for its user authentication.
I do not wish for users to reset their own password (for reasons which are not relevant here), so I have developed the following back end system to allow system administrators to reset the users password.
I have the following implementation:
Password Reset View:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ResetPasswordViewModel</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.NewPassword, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.NewPassword, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.NewPassword, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Reset Password" class="btn btn-default" />
</div>
</div>
</div>
}
AccountAdmin Controller
// GET: /AccountAdmin/ResetPassword
public ActionResult ResetPassword(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ResetPasswordViewModel model = new ResetPasswordViewModel() { Id = id };
return View(model);
}
//
// POST: /AccountAdmin/ResetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var removePassword = UserManager.RemovePassword(model.Id);
if (removePassword.Succeeded)
{
//Removed Password Success
var AddPassword = UserManager.AddPassword(model.Id, model.NewPassword);
if (AddPassword.Succeeded)
{
return View("PasswordResetConfirm");
}
}
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ResetPassword View Model
public class ResetPasswordViewModel
{
public string Id { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}