I was trying to change password in MVC and looked at the link "How to change password in asp.net mvc" but it requires me to add Old password, which I don't want, so if I am admin user of website, I would like to change password in MVC asp.net identity without using old password, how can I achieve that?
Yes, you can do that, you can change password in MVC using ASP.NET identity without needing old password of user, so here the code for Code it.
[HttpPost]
[ValidateAntiForgeryToken]
public async System.Threading.Tasks.Task<ActionResult> UpdatePassword(FormCollection formCollection)
{
//get user by it's unique ID
ApplicationUser user = await UserManager.FindByIdAsync(Convert.ToInt32( formCollection["Id"]));
// Use passwordHash to add new password
user.PasswordHash = UserManager.PasswordHasher.HashPassword(formCollection["Password"]);
//update user password
var result = await UserManager.UpdateAsync(user);
if (result.Succeeded)
{
// do something
}
}
return RedirectToAction("SomeAction");
}
Where, FormCollection
is getting User Id and New password from user.
Your View.cshtml can be like this
@using (Html.BeginForm("UpdatePassword", "ControllerName", FormMethod.Post, new { @class = "validatedForm" }))
{
@Html.AntiForgeryToken()
<input type="hidden" id="Id" name="Id" value="@ViewBag.Id" />
<div class="form-group">
@Html.Label("Email")
<input type="text" value="UserEmail" class="form-control" id="Email" name="Email" disabled />
</div>
<div class="form-group">
@Html.Label("Password")
@Html.TextBox("Password", "", new { @class = "form-control", type = "password"})
</div>
<div class="form-group">
@Html.Label("Confirm Password")
@Html.TextBox("ConfirmPassword", "", new { @class = "form-control", type = "password" })
</div>
<div class="form-group">
<input type="submit" value="Update" class="btn btn-primary" id="SubmitBtn" />
</div>
}
If you don't want to use PasswordHasher without any validation, try this
//Get User By Id
var user = await UserManager.FindByIdAsync(id);
//Generate Token
var token = await UserManager.GeneratePasswordResetTokenAsync(user);
//Set new Password
var result = await UserManager.ResetPasswordAsync(user, token, "YouN3wP@ssw0rd");
You can also check Forgot password functionality in MVC.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly