我使用ASP.Net Identity 2.1創建了兩個項目(MVC 5和Web API),我無法找到如何同時使用電子郵件和用戶名進行身份驗證(一個名爲Admin must使用用戶名和公共區域必須使用電子郵件地址進行身份驗證)。允許電子郵件和用戶名進行身份驗證
問題是,只有一種身份驗證方法,它不允許您指定是否要與電子郵件地址或用戶名進行比較。
SignInHelper.PasswordSignIn
我該怎麼做才能做到這一點?
我使用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);