ASP.NET Identity 2.1-密码重置无效令牌 [英] ASP.NET Identity 2.1 - Password Reset Invalid Tokens

查看:122
本文介绍了ASP.NET Identity 2.1-密码重置无效令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ASP.NET身份返回无效令牌".重置用户密码时的响应.

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

我尝试了以下操作:

  • URL在发送电子邮件之前对代码进行编码
  • URL编码&之前和之后解码代码
  • 复制代码以确保其与发送的内容匹配
  • 确保我的用户电子邮件已确认(听说这可能是一个问题)
  • 创建了自定义的UserManager/Store等.

这是我的电子邮件代码:

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

生成的URL:

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

最后我的重置代码:

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

内部结果为1个错误,Invalid token.

Inside the result is 1 error, Invalid token.

我创建UserManager方法:

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

我的Startup.Auth配置:

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:

  • ASP.NET Identity 2 - UserManager.ConfirmEmail Fails In Production
  • aspnet identity invalid token on confirmation email
  • http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-web-app-with-email-confirmation-and-password-reset#reset
  • Asp.NET - Identity 2 - Invalid Token Error
  • aspnet identity invalid token on confirmation email
  • https://aspnetidentity.codeplex.com/discussions/544368

感谢您提供有关此问题的帮助.

Thanks for any help with this problem.

推荐答案

您可以尝试使用此代码.

我分享了此链接:确认电子邮件上的ASPNET身份无效令牌

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

这篇关于ASP.NET Identity 2.1-密码重置无效令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆