允许电子邮件和用户名进行身份验证
问题描述:
我使用ASP.Net Identity 2.1创建了两个项目(MVC 5和Web API),我无法找到如何同时使用电子邮件和用户名进行身份验证(一个名为Admin must使用用户名和公共区域必须使用电子邮件地址进行身份验证)。允许电子邮件和用户名进行身份验证
问题是,只有一种身份验证方法,它不允许您指定是否要与电子邮件地址或用户名进行比较。
SignInHelper.PasswordSignIn
我该怎么做才能做到这一点?
答
SignInManager
你不与它的帮助,你需要使用UserManager
,多一点暗中捣鬼(这是专业术语!):
这是我有这样的场景:
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);
这会检查用户是否确认了电子邮件,如果用户被锁定并且在一定次数的尝试后锁定用户(考虑到启用了所有其他锁定设置)。
答
这样既允许
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);