如何在身份中使用电子邮件登录 2.



在 MVC5 Identity 2 SignInManager.PasswordSignInAsync 中,采用用户名登录。

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

但是我的用户名和电子邮件不一样。 但我想使用电子邮件地址登录。那么我该怎么做呢?谢谢

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

var user = UserManager.FindByEmail(email);

然后将 SignInManager 的密码登录异步与用户的用户名一起使用

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

或者在登录管理器中添加此方法(ASP.NET 标识讨论(

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。

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

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);
   }

IsValidEmailAddress是属性装饰[EmailAddress]验证属性的自定义变体,我们没有使用内置的,因为它不会对TLD进行长度检查,并允许像x@x.c这样的电子邮件地址

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);
    }

正则表达式模式:

public const string EMAIL_VALIDATION_PATTERN = @"^((([a-z]|d|[!#$%&'*+-/=?^_`{|}~]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])+(.([a-z]|d|[!#$%&'*+-/=?^_`{|}~]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])+)*)|((x22)((((x20|x09)*(x0dx0a))?(x20|x09)+)?(([x01-x08x0bx0cx0e-x1fx7f]|x21|[x23-x5b]|[x5d-x7e]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(\([x01-x09x0bx0cx0d-x7f]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))))*(((x20|x09)*(x0dx0a))?(x20|x09)+)?(x22)))@((([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])*([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))).)+(([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])*([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))){2,63}.?$";

相关内容

  • 没有找到相关文章

最新更新