0
votes

ASP.NET Identity is returning an 'Invalid token.' response when resetting a password for users.

I've tried the following:

  • URL Encode the code before sending email
  • URL Encode & Decode the code before and after
  • Copying the code to make sure it matches what was sent
  • Ensured my user email is confirmed (I heard that could be a problem)
  • Created a custom UserManager/Store etc.

This is my email code:

var user = await UserManager.FindByNameAsync(model.Email);

var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = Url.Action("ResetPassword", "Account", new { code }, "http");

var body = string.Format("Click here to reset your password: {0}", callbackUrl);
await UserManager.SendEmailAsync(user.Id, "Reset Password", body);

return View("~/Views/Account/Login.cshtml", model);

The generated URL:

http://localhost/Account/ResetPassword?code=XTMg3fBDDR77LRptnRpg7r7oDxz%2FcvGscq5Pm3HMe8RJgX0KVx6YbOeqflvVUINipVcXcDDq1phuj0GCmieCuawdgfQzhoG0FUH4BoLi1TxY2kMljGp1deN60krGYaJMV6rbkrDivKa43UEarBHawQ%3D%3D

Finally my reset code:

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

ModelState.AddModelError("","Invalid Password Please Try Again");
return View();

Inside the result is 1 error, Invalid token.

My create UserManager method:

public static CustomerUserManager Create(IdentityFactoryOptions<CustomerUserManager> options, IOwinContext context)
{
    var manager = new CustomerUserManager(new CustomerUserStore(context.Get<CustomerDbContext>()));

    // Configure validation logic for usernames
    manager.UserValidator = new UserValidator<Customer>(manager)
    {
        AllowOnlyAlphanumericUserNames = false,
        RequireUniqueEmail = true
    };

    // Configure validation logic for passwords
    manager.PasswordValidator = new PasswordValidator
    {
        RequiredLength = 6,
        RequireNonLetterOrDigit = true,
        RequireDigit = true,
        RequireLowercase = true,
        RequireUppercase = true,
    };

    manager.EmailService = new EmailService();

    var dataProtectionProvider = options.DataProtectionProvider;
    if (dataProtectionProvider != null)
    {
        manager.UserTokenProvider = new DataProtectorTokenProvider<Customer, string>(dataProtectionProvider.Create("ASP.NET Identity"));
    }

    return manager;
}

My Startup.Auth config:

app.CreatePerOwinContext(CustomerDbContext.Create);
app.CreatePerOwinContext<CustomerUserManager>(CustomerUserManager.Create);

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),

    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity =
            SecurityStampValidator.OnValidateIdentity<CustomerUserManager, Customer, string>
            (
                validateInterval: TimeSpan.FromMinutes(30),
                regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                getUserIdCallback: (id) => (id.GetUserId())
            )
    }
});

List of tried solutions:

Thanks for any help with this problem.

1
It looks like the code itself is Base 64 encoded. The tell tale sign is the double equals at the end (%3D%3D). Look at the token in your database and compare it to the one you just received. Also make sure there isn't a token expiration that is clearing the token from the database before you receive the email.Berin Loritsch

1 Answers

0
votes

You can try this code.

I shared this link: aspnet identity invalid token on confirmation email

var encodedCode= code.Base64ForUrlEncode();
var decodedCode= encodedCode.Base64ForUrlDecode();

public static class UrlEncoding
{
        public static string Base64ForUrlEncode(this string str)
        {
            byte[] encbuff = Encoding.UTF8.GetBytes(str);
            return HttpServerUtility.UrlTokenEncode(encbuff);
        }

        public static string Base64ForUrlDecode(this string str)
        {
            byte[] decbuff = HttpServerUtility.UrlTokenDecode(str);
            return Encoding.UTF8.GetString(decbuff);
        }
}