Invalid Token. while verifying email verification

2019-04-24 02:14发布

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

6条回答
forever°为你锁心
2楼-- · 2019-04-24 03:00

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.

查看更多
等我变得足够好
3楼-- · 2019-04-24 03:04

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!

查看更多
戒情不戒烟
4楼-- · 2019-04-24 03:05

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); 
查看更多
乱世女痞
5楼-- · 2019-04-24 03:10

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);
查看更多
混吃等死
6楼-- · 2019-04-24 03:16

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.

查看更多
虎瘦雄心在
7楼-- · 2019-04-24 03:19

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();
    }
查看更多
登录 后发表回答