【问题标题】:Using 2FA for password reset使用 2FA 进行密码重置
【发布时间】:2018-02-01 11:09:32
【问题描述】:

我的应用程序使用 Asp.Net Identity 并在 登录 时向我的 Auth 应用程序发送一个双因素代码。这是非常标准的(因为网上有很多示例)并使用 SendCode() 方法。我的理解是“魔术”是通过这一行完成的:

// Generate the token and send it
if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
  View("Error");
}

我的要求是确保用户在登录后更改密码时经历相同的 2FA 过程。

我的问题是当执行发送 2FA 代码的代码时:

if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
  View("Error");
}

我收到错误“找不到用户 ID”:

Server Error in '/MSPortal' Application.
UserId not found.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: UserId not found.

Source Error: 


Line 555:
Line 556:            // Generate the token and send it
Line 557:            if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
Line 558:            {
Line 559:                return View("Error");

我知道 SendTwoFactorCodeAsync() 会调用 GetVerifiedUserIdAsync(),但我的理解是,现在我已经使用 2FA 登录验证了用户。

有人知道我为什么会收到这个错误吗?

谢谢。

【问题讨论】:

  • Do not post images of code or errors! 图片和屏幕截图可以很好地添加到帖子中,但请确保帖子在没有它们的情况下仍然清晰有用。如果您发布代码或错误消息的图像,请确保您也复制并粘贴或直接在帖子中输入实际代码/消息。
  • 感谢 Rob 的提醒。

标签: asp.net-identity-2


【解决方案1】:

我通过覆盖 IdentityConfig.cs 中的 SendTwoFactorCodeAsync() 解决了这个问题。在这个覆盖中,我首先像往常一样调用 GetVerifiedUserIdAsync(),但如果它是 0,我会从当前 HttpContext 获取用户 ID。

我并不是说这是最好的方法,但这是我迄今为止所做的,它让我朝着实现 2FA 登录、更改密码和忘记密码的目标前进。

代码(如果我得到反馈可能会进行一些重构)是:

public override async Task<bool> SendTwoFactorCodeAsync(string provider)
{
    int userId = 0;
    try
    {
        userId = await GetVerifiedUserIdAsync();
        if (userId == 0)
        {
            userId = Convert.ToInt32(HttpContext.Current.User.Identity.GetUserId());
        }

        if (userId == 0)
            return false;
    }
    catch
    {
        return false;
    }

    var token = await UserManager.GenerateTwoFactorTokenAsync(userId, provider);

    // See IdentityConfig.cs to plug in Email/SMS services to actually send the code
    await UserManager.NotifyTwoFactorTokenAsync(userId, provider, token);
    return true;

    //return base.SendTwoFactorCodeAsync(provider);
}

【讨论】:

    猜你喜欢
    • 2018-02-13
    • 2021-10-31
    • 2019-07-25
    • 2015-03-12
    • 2020-07-17
    • 2018-01-16
    • 2023-03-08
    • 1970-01-01
    • 2016-04-10
    相关资源
    最近更新 更多