Invalid Token. while verifying email verification code using UserManager.ConfirmEmailAsync(user.Id, code)

generateemailconfirmationtokenasync
asp net identity email confirmation
email verification code in asp net c#
asp.net identity password reset token expiration
generatepasswordresettokenasync
asp net core identity confirm email invalid token
how to get user password in asp net identity
send confirmation email after registration in asp net mvc

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


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!

UserManager.ConfirmEmailAsync always returns "Invalid Token , Invalid Token. while verifying email verification code using UserManager.​ConfirmEmailAsync(user.Id, code) [Answered]RSS. 6 replies. Last  Invalid Token. while verifying email verification code using UserManager.ConfirmEmailAsync(user.Id, code) [Answered] RSS 6 replies Last post Aug 06, 2014 12:51 PM by KT.NET


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);

Asp.Net Identity Invalid Token for password reset or email confirmation, Hey, In my application running, I am not able to confirm user's emails as UserManager. I have verified in every way that the token issued (before U.. While investigating I stepped into the Identity source code and found that  Invalid Token. while verifying email verification code using UserManager.ConfirmEmailAsync(user.Id, code) 67 Asp.NET Identity 2 giving “Invalid Token” error


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.

Invalid Token Error on Email Confirmation in Aspnet Identity, And the same question comes up quite often: users try to confirm Password Reset Token vs Email Confirmation Token If you explore UserManager object, you will find 3 public methods that can generate you a token: You see it is taking a purpose string and a User.Id . If you look on the source code of  22 Invalid Token. while verifying email verification code using UserManager.ConfirmEmailAsync(user.Id, code) 16 Insert line break in wrapped cell via code 10 How to put border round images in Outlook by default


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();
    }

Asp.NET Identity 2 giving “Invalid Token” error, Invalid Token Error on Email Confirmation in Aspnet Identity are getting "invalid token" error on confirming email using UserManager.ConfirmEmailAsync, then there might be two reasons: GenerateEmailConfirmationToken(userID)); on one server and the mail confirmation code is on another server. IBM InfoSphere Master Data Management Collaboration Server issues these error messages.


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); 

[Solved] Getting Invalid Token from Browser, I'm using Asp.Net-Identity-2 and I'm trying to verify email verification code My Action to check the token is (here, I always get “Invalid Token” when I check the result): ioe) { // ConfirmEmailAsync throws when the id is not found. return string code = UserManager.GeneratePasswordResetToken(user.Id);. Generated because the the currently used certificate or crl's byte[] is malformed and thus cannot be used in the application. To verify please check the certificate or crl again using other available debug tools and use correct certificate or crl.


St4k, It looks like you've forgotten to URL-encode the code when you created the confirmation URL. For backwards-compatibility, browsers treat a +  More than one XPath was provided (either to data or as a function). The first function XPath provided in the Query component of the Process URI takes precedence over a data XPath in the Path component.


ASP.NET Core Identity invalid token on confirmation email, NET Identity 2 Email Confirmation Invalid Token. 1 I'm having a odd problem with GenerateEmailConfirmationTokenAsync and ConfirmEmailAsync methods. The odd thing is I can never reproduce any error while creating user and after getting the mail, confirming it. string code = await UserManager. Asp.net mvc - Invalid Token. while verifying email Stackoverflow.com 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.


In order to generate that link I have to generate a code using Identity. email) { //_userManager is an instance of UserManager<User> var userEntity = await get the PUT request, grab the code and validate it using Identity like this: [HttpPut] link); } and when receiving back the code during the PUT request [HttpPut]  How to build a boilerplate authentication system in React including email sign up & verification, authentication & role based authorization, forgot password & reset password functionality, view & update my profile section, and admin only section for managing all user accounts.