8

我正在研究在 MVC 中实现两因素身份验证,类似于 Google 的身份验证器。

由于某些用户没有双重身份验证设置,我们希望使用两步过程 - 一个屏幕输入用户名和密码,另一个屏幕输入一次性密码。

我的困难是如何在用户输入一次性密码时安全地存储用户名和密码?目前我们收到密码并立即拒绝或发出 cookie,因此我们不会将密码存储在任何地方。但是,通过两步,我们不能立即发出 cookie,因为用户可以简单地导航到另一个操作。同样,我不想将密码作为表单中的隐藏元素发回给用户。

这种情况的标准做法是什么?

我能想到的最好的方法是将用户名和密码存储在会话中,但我不确定这有多安全。

4

3 回答 3

8

While an answer has already been accepted I thought I would add a different way. You don't need to log the user in when you validate their username and password combination, if they have provided the correct details all you need to store in the temporary data is their username or their profile if you want, then redirecting them to the second factor page, which only once they have provided the correct one time password do you actually log the user in.

This method avoids the need for having additional attributes, which can be a pain for consistency.

This is the relevant snippet on how to achieve it

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            var profile = MvcTFAProfile.GetProfile(model.UserName);

            if (profile.UsesTwoFactorAuthentication)
            {
                TempData[CurrentUserTempDataKey] = profile;
                TempData[RememberMeTempDataKey] = model.RememberMe;
                return RedirectToAction("SecondFactor", new {returnUrl = returnUrl});
            }

            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            return RedirectToLocal(returnUrl);
        }
    }

    // If we got this far, something failed, redisplay form
    ModelState.AddModelError("", "The user name or password provided is incorrect.");
    return View(model);
}

The following link contains all the details on how to implement this in ASP.NET MVC, the article targets Google Authenticator, which may not be what you're working with but the principle of how to log the user in etc. is the same; https://samjenkins.com/mvc-two-factor-authentication/

于 2013-09-08T20:43:35.810 回答
5

实际上,您不需要存储密码并等待您的身份验证,直到通过第二步。您可以分别执行两个步骤的身份验证(每个步骤都像通常的身份验证:您立即进行身份验证或拒绝),并相应地授予通过第一步和第二步的用户适当的权限。

具体来说,您可以创建自己的 Authorize 属性AuthorizeConfirmedAttributeAuthorizeAttribute并将其用于身份验证的第二步。因此,在您生成屏幕以输入一次性密码的控制器中,您使用通常的[Authorize]属性,确保用户通过了第一步的身份验证。在所有其他操作中,您使用该[AuthorizeConfirmed]属性来确保用户通过了您的身份验证的两个步骤。

于 2013-07-31T06:54:14.450 回答
1

您应该查看 ASP.NET Identity 以获得两因素身份验证的示例流程。以下帖子包含更多信息和示例链接http://blogs.msdn.com/b/webdev/archive/2014/02/11/announcing-preview-of-microsoft-aspnet-identity-2-0-0- beta1.aspx

于 2014-02-19T06:37:31.220 回答