0

I'm trying to have the confirm email validate a new user account. The token is created and emailed to the user which receive an email with a link to validate the account. When the user clicks on the link, I'm getting INVALID TOKEN.

It is hosted on Godaddy (not sure if it makes any difference)

While debugging the code, I find out that the token being sent to validate is the same generated initially, with the difference that now its lowercase, can this be the problem?

The code to generate the token and email it

private async Task<string> SendEmailConfirmationTokenAsync(string userID, string subject)
{
   string _code = await UserManager.GenerateEmailConfirmationTokenAsync(userID); 
   var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = userID, code = _code }, protocol: Request.Url.Scheme);
   await UserManager.SendEmailAsync(userID, subject, "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

   return callbackUrl;
}

To confirm the token/email:

[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
    if (userId == null || code == null)
    {
        return View("Error");
    }

    var result = await UserManager.ConfirmEmailAsync(userId, code);
    if (result.Succeeded)
    {
        return RedirectToAction("Create", "Users", new { id = userId });
    }

    AddErrors(result);
    ViewBag.errorMessage = "Error: " + result.Errors;
    return View("Error");
}

Also I added machineKey to web.config.

<machineKey validationKey="key" decryptionKey="key" validation="SHA1" decryption="AES" />

All the time I'm getting the error INVALID TOKEN

2 Answers2

0

Encode your code before sending it via email:

private async Task<string> SendEmailConfirmationTokenAsync(string userID, string subject)
{
   string _code = await UserManager.GenerateEmailConfirmationTokenAsync(userID); 
     _code = HttpUtility.UrlEncode(_code);
   var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = userID, code = _code }, protocol: Request.Url.Scheme);
   await UserManager.SendEmailAsync(userID, subject, "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

   return callbackUrl;
}
Mohsin Mehmood
  • 4,156
  • 2
  • 12
  • 18
0

It's unbelievable but the solution was creating a new project and bringing everything to it.

I think something happened while VS created the project that caused the problem.

Thanks for all halp