允许用于身份验证的电子邮件和用户名

时间:2014-09-01 19:29:45

标签: asp.net-identity-2

我正在使用ASP.Net Identity 2.1创建两个项目(MVC 5和Web API),我无法找到如何使用电子邮件和用户名进行身份验证(一个名为Admin的区域必须使用用户名公共区域必须使用电子邮件地址进行身份验证。)

问题是只有一种身份验证方法,它不允许您指定是否要与电子邮件地址或用户名进行比较。

SignInHelper.PasswordSignIn

我该怎么做才能实现这个目标?

2 个答案:

答案 0 :(得分:3)

SignInManager你不会帮忙吗,你需要使用UserManager和更多jiggery-pokery(这是技术术语!):

这就是我对这种情况的看法:

var unauthUserByUsername = await userManager.FindByNameAsync(command.UserName);
var unauthUserByEmail = await userManager.FindByEmailAsync(command.UserName);

var unauthenticatedUser = unauthUserByUsername ?? unauthUserByEmail;
if (unauthenticatedUser == null)
{
    logger.Warn("User {0} is trying to login but username is not correct", command.UserName);
    return View(); // stop processing
}

var loggedInUser = await userManager.FindAsync(unauthenticatedUser.UserName, command.Password);
if (loggedInUser == null)
{
    // username is correct, but password is not correct
    logger.Warn("User {0} is trying to login with incorrect password", command.UserName);
    await userManager.AccessFailedAsync(unauthenticatedUser.Id);
    return View(); // stop processing
}

// Ok, from now on we have user who provided correct username and password.

// and because correct username/password was given, we reset count for incorrect logins.
await userManager.ResetAccessFailedCountAsync(loggedInUser.Id);

if (!loggedInUser.EmailConfirmed)
{
    logger.Warn("User {0} is trying to login, entering correct login details, but email is not confirmed yet.", command.UserName);
    return View("Please confirm your email"); // stop processing
}

if (await userManager.IsLockedOutAsync(loggedInUser.Id))
{
    // when user is locked, but provide correct credentials, show them the lockout message
    logger.Warn("User {0} is locked out and trying to login", command.UserName);
    return View("Your account is locked");
}

logger.Info("User {0} is logged in", loggedInUser.UserName);

// actually sign-in.
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
await userManager.SignInAsync(authenticationManager, loggedInUser, false);

这将检查用户是否已确认电子邮件,用户是否已被锁定并在一定次数的尝试后锁定用户(假设已启用所有其他锁定设置)。

答案 1 :(得分:1)

这两种方式都是允许的

  var userEmail = await UserManager.FindByEmailAsync(model.Login);

            if (userEmail == null)
            {
                var user = await UserManager.FindByNameAsync(model.Login);
                if (user == null)
                {
                    model.Login = "";
                }

            }
            else
            {
                model.Login = userEmail.UserName;
            }

var result = await SignInManager.PasswordSignInAsync(model.Login, model.Password, model.RememberMe, shouldLockout: false);
相关问题