如何使用身份2中的电子邮件登录?

时间:2014-12-16 06:33:09

标签: asp.net-mvc asp.net-mvc-5 asp.net-identity identity asp.net-identity-2

在MVC5中,Identity2 SignInManager.PasswordSignInAsync获取登录用户名。

var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);

但我的用户名和电子邮件不一样。但我想通过电子邮件地址登录。所以我该怎么做? 感谢

2 个答案:

答案 0 :(得分:32)

通过电子邮件从UserManager获取用户。

var user = UserManager.FindByEmail(email);

然后使用SignInManager的PasswordSignInAsync和用户的用户名

var result = await SignInManager
.PasswordSignInAsync(user.UserName,password,isPersistent,shouldLockout);

或者在SignInManager中添加此方法(ASP.NET Identity discussion

public async Task<SignInStatus> PasswordEmailSignInAsync(string email, string password, bool isPersistent, bool shouldLockout)
{
      var user =  UserManager.FindByEmail(email);
      return await PasswordSignInAsync(user.UserName,password,isPersistent,shouldLockout);
}

然后使用与PasswordSignInAsync相同但使用用户电子邮件而不是usermane。

答案 1 :(得分:2)

我们希望能够允许我们的用户通过用户名或电子邮件登录。这是我们的设置方式:

SELECT Object A ,Object B, Object C From Table1 WHERE Object A > Object B

IsValidEmailAddress是属性修饰[EmailAddress]验证属性的自定义变体,我们没有使用内置的,因为它没有对TLD进行长度检查,并且允许使用电子邮件地址,例如x @ xc

var isEmail = ValidationManager.IsValidEmailAddress(model.Username);

SignInStatus result = SignInStatus.Failure;

if (!isEmail)
   {
       result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, false);
   }
   else
   {
       var user = await UserManager.FindByEmailAsync(model.Username);
       if (user != null)
           result = await SignInManager.PasswordSignInAsync(user.UserName, model.Password, model.RememberMe, false);
   }

RegEx模式:

public static bool IsValidEmailAddress(string email)
    {
        if (string.IsNullOrEmpty(email))
            return false;

        var pattern = GlobalConstants.EMAIL_VALIDATION_PATTERN;
        const RegexOptions options = RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture;

        var emailValidator = new Regex(pattern,options);

        return emailValidator.IsMatch(email);
    }