19

I have recently migrated Asp.net identity 1.0 to 2.0 . I am trying to verify email verification code using below method. But i am getting "Invalid Token" error message.

public async Task<HttpResponseMessage> ConfirmEmail(string userName, string code)
        {
            ApplicationUser user = UserManager.FindByName(userName);
            var result = await UserManager.ConfirmEmailAsync(user.Id, code);
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

Generating Email verification token using below code (And if i call ConfirmEmailAsyc immediate after generating token, which is working fine). But when i am calling using different method which is giving error

public async Task<HttpResponseMessage> GetEmailConfirmationCode(string userName)
        {
            ApplicationUser user = UserManager.FindByName(userName);
            var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
            //var result = await UserManager.ConfirmEmailAsync(user.Id, code);
            return Request.CreateResponse(HttpStatusCode.OK, code);
        }

Please help

Kumar T
  • 191
  • 1
  • 1
  • 5
  • Did you ever find the answer to this? I have been working on this all day, and it's does appear to work at all. – Rogala Aug 11 '14 at 21:47
  • 3
    Hi, Its working now.. Its because of my oversight. After url encode and decode of verification tokens it working. Because I had some plus(+) symbols inside token – Kumar T Aug 13 '14 at 13:55
  • Kumar , can you please share what you did to solve it ? – Pit Digger Aug 18 '14 at 17:51
  • 1
    @PitDigger - A simple fix is to use the Replace(" ","+"); – Rogala Sep 02 '14 at 12:50
  • 1
    In my case (Asp.Net Core 3.0) it seems that the scaffolded pages introduced this error. See my [answer](https://stackoverflow.com/a/58581494/5148420) here. – jhhwilliams Oct 27 '19 at 17:05

6 Answers6

34

I found you had to encode the token before putting it into an email, but not when checking it afterwards. So my code to send the email reads:

                // Send an email with this link 
                string code = UserManager.GenerateEmailConfirmationToken(user.Id);

                // added HTML encoding
                string codeHtmlVersion = HttpUtility.UrlEncode(code);

                // for some weird reason the following commented out line (which should return an absolute URL) returns null instead
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                string callbackUrl = "(your URL)/Account/ConfirmEmail?userId=" +
                    user.Id + "&code=" + codeHtmlVersion;

                // Send an email with this link using class (not shown here)
                var m = new Email();

                m.ToAddresses.Add(user.Email);
                m.Subject = "Confirm email address for new account";

                m.Body =
                    "Hi " + user.UserName + dcr +
                    "You have been sent this email because you created an account on our website.  " +
                    "Please click on <a href =\"" + callbackUrl + "\">this link</a> to confirm your email address is correct. ";

The code confirming the email then reads:

// user has clicked on link to confirm email
    [AllowAnonymous]
    public async Task<ActionResult> ConfirmEmail(string userId, string code)
    {

        // email confirmation page            
        // don't HTTP decode

        // try to authenticate
        if (userId == null || code == null)
        {
            // report an error somehow
        }
        else
        {

            // check if token OK
            var result = UserManager.ConfirmEmail(userId, code);
            if (result.Succeeded)
            {
                // report success
            }
            else
            {
                // report failure
            }
        }

Worked in the end for me!

Andy Brown
  • 5,309
  • 4
  • 34
  • 39
5

Hi this happened if I am getting the url(full) and calling to the api throught WebClient. The code value have to be Encoded before sending the call.

code = HttpUtility.UrlEncode(code); 
Mahendra
  • 447
  • 6
  • 7
3

Hope the issue got resolved. Otherwise below is the link for the solution which worked well.

Asp.NET - Identity 2 - Invalid Token Error

Simply use:

emailConfirmationCode = await 
UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
UserManager.ConfirmEmailAsync(userId, code1);
Community
  • 1
  • 1
Dinesh
  • 41
  • 5
3

My issue was slightly different.

I created my own IUserStore and one thing I was doing wrong was setting the SecurityStamp to null if there was no value.

The security stamp is used to generate the token but it's replaced by an empty string when the token is generated, however it is not replaced when validating the token, so it ends up comparing String.Empty to null, which will always return false.

I fixed my issue by replacing null values for String.Empty when reading from the database.

Alberto Sadoc
  • 107
  • 2
  • 5
  • If you try both to verify PhoneNumber and Email then this InvalidToken could happen due to SecurityStamp being altered when calling ChangePhoneNumberAsync() to verity PhoneNumber. Some more insights about this topic if this is your problem: https://stackoverflow.com/questions/36182915/invalid-token-in-confirmemail-due-to-changed-securitystamp – toralux Jun 03 '21 at 20:56
3

Had the same issue. The fix was to HTML encode the token when generating the link, and when confirming - HTML decode it back.

    public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);
            if (user == null )
            {
                // Don't reveal that the user does not exist or is not confirmed
                return RedirectToAction(nameof(ForgotPasswordConfirmation));
            }

            var code = await _userManager.GeneratePasswordResetTokenAsync( user );

            var codeHtmlVersion = HttpUtility.UrlEncode( code );
            var callbackUrl = Url.ResetPasswordCallbackLink(user.Id, codeHtmlVersion, Request.Scheme);
            await _emailSender.SendEmailAsync(
                model.Email, 

                $"You can reset your password by clicking here: <a href='{callbackUrl}'>link</a>", 
                _logger );
            return RedirectToAction(nameof(ForgotPasswordConfirmation));
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

    public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        var user = await _userManager.FindByEmailAsync(model.Email);
        if (user == null)
        {
            // Don't reveal that the user does not exist
            return RedirectToAction(nameof(ResetPasswordConfirmation));
        }

        var codeHtmlDecoded = HttpUtility.UrlDecode( model.Code );

        var result = await _userManager.ResetPasswordAsync(user, codeHtmlDecoded, model.Password);
        if (result.Succeeded)
        {
            return RedirectToAction(nameof(ResetPasswordConfirmation));
        }
        AddErrors(result);
        return View();
    }
Michail Lukow
  • 171
  • 1
  • 7
  • The concept here was what I needed to get stuff working, just don't do what I did: I was already encoding the token using AspNetCore.WebUtilities.WebEncoders for the Email link, but then I was trying to use HttpUtility (from the code above) to do the Decoding in the response to clicking the link. If you encode with WebUtilities.WebEncoders, be sure to Decode with WebUtilities.WebEncoders as well! see @walter33's Encode/Decode here: https://stackoverflow.com/questions/25405307/asp-net-identity-2-giving-invalid-token-error – StackOverflowUser May 03 '23 at 08:40
2

We had the same issue, Load balancing was causing this problem. Adding a <machineKey validationKey="XXX" decryptionKey="XXX" validation="SHA1" decryption="AES"/> in web.config file solved the problem. All your servers need to have the same machine key to verify previously generated code.

Hope this helps.

Arkadas Kilic
  • 2,416
  • 2
  • 20
  • 16