Asp.NET - 身份2 - 无效的令牌错误 [英] Asp.NET - Identity 2 - Invalid Token Error

查看:269
本文介绍了Asp.NET - 身份2 - 无效的令牌错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I'm使用的 Asp.Net身份-2 和我正尝试使用下面的方法来验证电子邮件验证code。但我得到一个无效令牌错误消息。

I´m using Asp.Net-Identity-2 and I´m trying to verify email verification code using the below method. But I am getting an "Invalid Token" error message.


  • 我的应用程序的用户管理器是

public class AppUserManager : UserManager<AppUser>
{
public AppUserManager(IUserStore<AppUser> store) : base(store) { }

    public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options, IOwinContext context)
    {
        AppIdentityDbContext db = context.Get<AppIdentityDbContext>();
        AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db));

        manager.PasswordValidator = new PasswordValidator { 
            RequiredLength = 6,
            RequireNonLetterOrDigit = false,
            RequireDigit = false,
            RequireLowercase = true,
            RequireUppercase = true
        };

        manager.UserValidator = new UserValidator<AppUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = true,
            RequireUniqueEmail = true
        };

        var dataProtectionProvider = options.DataProtectionProvider;

        //token life span is 3 hours
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider =
               new DataProtectorTokenProvider<AppUser>
                  (dataProtectionProvider.Create("ConfirmationToken"))
               {
                   TokenLifespan = TimeSpan.FromHours(3)
               };
        }

        //defining email service
        manager.EmailService = new EmailService();

        return manager;
    } //Create

  } //class

} //namespace


  • 我的行动来生成令牌是(即使我在这里检查的道理,我得到无效令牌消息)

  • My Action to generate the token is (Even if I check the token here, I get "Invalid token" message)

    [AllowAnonymous]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult ForgotPassword(string email)
    {
        if (ModelState.IsValid)
        {
            AppUser user = UserManager.FindByEmail(email);
            if (user == null || !(UserManager.IsEmailConfirmed(user.Id)))
            {
                // Returning without warning anything wrong...
                return View("../Home/Index");
    
            } //if
    
            string code = UserManager.GeneratePasswordResetToken(user.Id);
            string callbackUrl = Url.Action("ResetPassword", "Admin", new { Id = user.Id, code = HttpUtility.UrlEncode(code) }, protocol: Request.Url.Scheme);
    
            UserManager.SendEmail(user.Id, "Reset password Link", "Use the following  link to reset your password: <a href=\"" + callbackUrl + "\">link</a>");
    
            //This 2 lines I use tho debugger propose. The result is: "Invalid token" (???)
            IdentityResult result;
            result = UserManager.ConfirmEmail(user.Id, code);
    
    
        }
    
        // If we got this far, something failed, redisplay form
        return View();
    
    } //ForgotPassword
    


  • 我的行动来检查令牌是(在这里,我总是得到无效令牌当我检查结果)

  • My Action to check the token is (here, I always get "Invalid Token" when I check the result)

    [AllowAnonymous]
    public async Task<ActionResult> ResetPassword(string id, string code)
    {
    
        if (id == null || code == null)
        {
            return View("Error", new string[] { "Invalid params to reset password." });
        }
    
        IdentityResult result;
    
        try
        {
            result = await UserManager.ConfirmEmailAsync(id, code);
        }
        catch (InvalidOperationException ioe)
        {
            // ConfirmEmailAsync throws when the id is not found.
            return View("Error", new string[] { "Error to reset password:<br/><br/><li>" + ioe.Message + "</li>" });
        }
    
        if (result.Succeeded)
        {
            AppUser objUser = await UserManager.FindByIdAsync(id);
            ResetPasswordModel model = new ResetPasswordModel();
    
            model.Id = objUser.Id;
            model.Name = objUser.UserName;
            model.Email = objUser.Email;
    
            return View(model);
    
        }
    
    
        // If we got this far, something failed.
        string strErrorMsg = "";
        foreach(string strError in result.Errors)
        {
            strErrorMsg += "<li>" + strError + "</li>";
        } //foreach
    
    
        return View("Error", new string[] { strErrorMsg });
    
    
    } //ForgotPasswordConfirmation
    


  • 我不知道什么是丢失或什么是错的。

    I don´t know what is missing or what's is wrong.

    感谢您的帮助...

    推荐答案

    由于要生成令牌密码重置在这里:

    Because you are generating token for password reset here:

    string code = UserManager.GeneratePasswordResetToken(user.Id);
    

    但实际上试图验证电子邮件令牌:

    But actually trying to validate token for email:

    result = await UserManager.ConfirmEmailAsync(id, code);
    

    这是2个不同的令牌。

    These are 2 different tokens.

    在你的问题,你说你尝试验证电子邮件,但您的code是用于重置密码。哪一个是你在做什么?

    In your question you say that you are trying to verify email, but your code is for password reset. Which one are you doing?

    如果您需要确认电子邮件,然后通过

    If you need email confirmation, then generate token via

    var emailConfirmationCode = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
    

    并通过

    var confirmResult = await UserManager.ConfirmEmailAsync(userId, code);
    

    如果你需要重新设置密码,产生这样的标记:

    If you need password reset, generate token like this:

    var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
    

    和确认它是这样的:

    var resetResult = await userManager.ResetPasswordAsync(user.Id, code, newPassword);
    

    这篇关于Asp.NET - 身份2 - 无效的令牌错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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