1
votes

A lot of people posted about this but could not get anything to work. I am trying to get the user's username and password on an Asp.net form (the same username and password which the user uses to login to their computer on a domain).

I am using the PrincipalContext to validate the user.

enter image description here

Although I provide valid username and password, but pc.ValidateCredentials always returns false.

This is the first time I am doing User Authentication through Active Directory and have no idea what else do I require to successfully validate a user from Active Directory.

Do I need to provide information in the Container and Name properties on the PrincipalContext Object as it appears to be null.

enter image description here

Currently I am running this code from local machine which is on domain.

2
Maybe you have to prefix the domain to username, i.e. "DOMAIN\\" + txtUsername.Text.Trim()Wernfried Domscheit

2 Answers

4
votes

Do you have the correct domain? Maybe it is called different than 'DOMAIN', try this one:

  private bool Authenticate(string user, string password)
  {
        using ( var context = new PrincipalContext(ContextType.Domain, Environment.UserDomainName) ) {
           return context.ValidateCredentials(user.Trim(), password.Trim());
        }
  }
0
votes

Please use below function

private bool AuthenticateAD(string userName, string password, string domain, out string message)
{

    message = "";       

    DirectoryEntry entry = new
        DirectoryEntry("LDAP://" + domain, userName, password);
    try
    {
        object obj = entry.NativeObject;
        DirectorySearcher search = new DirectorySearcher(entry);
        search.Filter = "(SAMAccountName=" + userName + ")";
        search.PropertiesToLoad.Add("cn");
        SearchResult result = search.FindOne();
        if (null == result)
        {
            return false;
        }           

    }
    catch (Exception ex)
    {
        message = ex.Message;
        return false;
        //throw new Exception("Error authenticating user. " + ex.Message);
    }

    return true;
}