I'm making a function to reset the password of a user using ASP.NET Identity. However, the token is not being picked up in my controller. When I submit the form, it says
"The Token field is required."
Why does it not pick up my token? Following code is being used to generate the resetLink:
var user = _userManager.FindByNameAsync(email).Result;
if (user == null || !_userManager.IsEmailConfirmedAsync(user).Result)
{
ViewBag.Message = "Error while resetting your password!";
return View("ResetPassword");
}
var token = _userManager.
GeneratePasswordResetTokenAsync(user).Result;
var resetLink = Url.Action("SetPassword",
"Auth", new { token },
protocol: HttpContext.Request.Scheme);
This generates the link: http://localhost:50015/adviseur/auth/setpassword?token=someverylongnumbers
This link goes to the following view, viewmodel and controller: AuthController.cs
[HttpGet]
public IActionResult SetPassword()
{
return View();
}
SetPassword.cshtml
@model SetPasswordModel
<h1>Set Your Password</h1>
<form asp-controller="Auth"
asp-action="RequestNewPassword"
method="post">
<input type="hidden" asp-for="Token" />
<table>
<tr>
<td><label asp-for="UserName"></label></td>
<td><input asp-for="UserName" /></td>
</tr>
<tr>
<td>
<label asp-for="Password">
New Password
</label>
</td>
<td><input asp-for="Password" /></td>
</tr>
<tr>
<td>
<label asp-for="ConfirmPassword">
Confirm New Password
</label>
</td>
<td><input asp-for="ConfirmPassword" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit"
value="Reset Password" />
</td>
</tr>
</table>
<div asp-validation-summary="All"></div>
</form>
SetPasswordModel.cs:
#region Using
using System.ComponentModel.DataAnnotations;
#endregion
namespace x.Areas.Adviseur.ViewModels
{
public class SetPasswordModel
{
[Required]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
public string ConfirmPassword { get; set; }
[Required]
public string Token { get; set; }
}
}
The form makes the request to the following controller:
[HttpPost]
public IActionResult RequestNewPassword(SetPasswordModel obj)
{
User user = _userManager.FindByNameAsync(obj.UserName).Result;
IdentityResult result = _userManager.ResetPasswordAsync(user, obj.Token, obj.Password).Result;
if (result.Succeeded)
{
ViewBag.Message = "Password reset successful!";
return View("Login");
}
else
{
ViewBag.Message = "Error while resetting the password!";
return View("SetPassword");
}
}