cell cell - 1 month ago 10
C# Question

Reset Password Functionality generates an invalid token

I am trying to develop Reset Password functionality in my Web API. The Email generation is performed in the Rest Web Service(Web API). Once the user receives the generated email with link, when he clicks the link, the user should be redirected to ResetPasswordPage residing in MVC Web Site(the Web Page is not in Web API, it is in Website developed by my colleague) residing in a different port.
When I click on the ResetPassword page, it opens up the Reset Password Web page.. and I click on Submit button, I get an 'Invalid Token' message.

The Web API(REST Web Service) code is as below

string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
code = HttpUtility.UrlEncode(code);
string forgotPasswordHost = System.Configuration.ConfigurationManager.AppSettings["ForgotPasswordURL"];
string forgotPasswordURL = Url.Route("URLApi", new {controller = "ResetPassword", userId = user.Id, code = code });
try
{
//await UserManager.SendEmailAsync(user.Id, "Reset Password", $"{url}");
await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + forgotPasswordHost + forgotPasswordURL + "\">here</a>");
}
catch (Exception e)
{
return new Status
{
status = "Invalid Input"
};
}


On Clicking the URL, it goes to the below code in Website

[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
return code == null ? View("Error") : View();
}


I get Invalid token from the below method (This is the WebSite Code)

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
AddErrors(result);
return View();
}


And on clicking the email link, the Web Page opens up. But I noticed that the value of '_RequestVerificationToken' is different when the web page gets opened and after the page is Submitted.
Any help will be appreciated

Answer

Found the answer. I referred the below link : http://www.gunaatita.com/Blog/Invalid-Token-Error-on-Email-Confirmation-in-Aspnet-Identity/1056

It was due to the machine key generated by Web API and MVC. Configuring the same machine key on both Web API and MVC solved the 'Invalid Token' issue.

Comments