如何在登录ASP.net Identity之前验证用户的用户名和密码?

时间:2017-01-13 21:03:36

标签: c# asp.net asp.net-membership

在我的ASP.Net应用程序中,想要在将用户登录到应用程序之前验证用户的用户名和密码。我使用ASP.net Identity框架作为成员资格。

想要确定输入的用户名和密码是否存在。 类似于Membership.ValidateUser(username,password)的东西,在默认会员资格中使用但不能与ASP.net Identity一起使用。 试过这个,但没有运气?

var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();

var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();

var user = manager.Find(userName,Password);

2 个答案:

答案 0 :(得分:8)

var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
var user = manager.FindByName(Email.Text);

//check for credentials before sign in ..    
var validCredentials = signinManager.UserManager.CheckPassword(user, Password.Text);
if (validCredentials)
{
    //sample code to run if user's credentials is valid and before login
    if(!manager.IsInRole(user.Id, "Administrators"))
    {
       FailureText.Text = "you need a higher permission level in order to login";
       return;
    }
}

//then sign in
var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);

答案 1 :(得分:-1)

我使用这样的东西:

public static bool ValidateUser(string Email, string Password)
    {
        var user = UserManager.FindByName(Email);
        return SignInManager.UserManager.CheckPassword(user, Password); 
    }