29

I'm using DirectorySearcher to search for a user entry in LDAP server.

DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://myserver/OU=People,O=mycompany";
de.AuthenticationType = AuthenticationTypes.None;

DirectorySearcher deSearch = new DirectorySearcher();

deSearch.SearchRoot = de;
deSearch.Filter = "(uid=" + model.UserName + ")";

SearchResult result = deSearch.FindOne();

I'm able to get th intended output in result variable.
However If I try to authenticate the same user by providing password in directory entry, I always get following error.

"The user name or password is incorrect."

DirectoryEntry entry = new DirectoryEntry("LDAP://myserver/OU=People,O=mycompany", username, password);
DirectorySearcher search = new DirectorySearcher(
    entry,
    "(uid=" + username + ")",
    new string[] { "uid" }
);

search.SearchScope = System.DirectoryServices.SearchScope.Subtree;
SearchResult found = search.FindOne();   ->>>>>this is where I get wrong credential error.

The username and password are for the user I want to authenticate.

Can anyone tell me what I'm doing wrong here or how to debug this.

Tolga Evcimen
  • 7,112
  • 11
  • 58
  • 91
sunny days
  • 837
  • 1
  • 13
  • 26
  • 1
    Does your LDAP server require authentification before querying it ? – T. Fabre Jul 19 '12 at 13:19
  • no it doesn't require authentication for search. I can search as anonymous user as well. I have a web based tool where I need to implement LDAP authentication so that only authentic users have access to it. – sunny days Jul 19 '12 at 14:02

2 Answers2

52

This username, password within this line:

DirectoryEntry("LDAP://myserver/OU=People,O=mycompany", username, password);

should be for an account that has permission for directory lookup. It could be a service account or testing purpose try with your own. This shouldn't be the user/pass of someone who you are trying to authenticate.

If you want to authenticate, you can use following steps using PrincipalContext:

using(var context = new PrincipalContext(ContextType.Domain, "mydomain", "mydomain\serviceAcct", "serviceAcctPass")) {
 //Username and password for authentication.
 return context.ValidateCredentials(username, password); 
}

"serviceAcct" = an account within domain users that has permission for directory lookup. "serviceAcctPass" = password for that service account. As I said, for testing you can try with your own user/pass context.

Also, make sure supplied username has either "domain\username" or "username@domain" formatting.

mattruma
  • 16,589
  • 32
  • 107
  • 171
loopedcode
  • 4,863
  • 1
  • 21
  • 21
  • ok so what I'm providing here is wrong. Can you please tell me what should be done to authenticate any ordinary user with LDAP by providing his username and password? or redirect me to some tutorial or link. Thx – sunny days Jul 19 '12 at 14:01
  • 2
    Reading from another comment that you posted above, it seems your domain doesn't require authenticated user for lookup. If that is the case, you can probably use default constructor of PrincipalContext instead of user/pass constructor. – loopedcode Jul 19 '12 at 14:25
  • how to use directoryEntry and principlacontext together ? bcz if i try to use Ldap in principalcontext it brings an error that it cant connect to system – Salman Feb 25 '15 at 13:04
  • how could this point to the LDAP server at `LDAP://myserver/OU=People,O=mycompany`? it looks just like the LDAP server should be right in the current domain for this to work. – Hopeless Aug 01 '18 at 02:09
  • Note that DirectoryEntry("LDAP://myserver/OU=People,O=mycompany", username, password); authenticates against both SamAccountName or "mail", that is to say, the e-mail address works as username, too. – Stefan Steiger Dec 04 '18 at 16:14
  • How to I pass IP address of domain name along with domain name in LDAP Authentication? – Mukund Thakkar Jun 10 '19 at 13:11
  • How to authenticate if the service account password is null? – Vara Prasad.M Aug 30 '21 at 00:29
0

Here we are getting the active directory user details and we can use DomainName and UserRole from web.config file

bool isAdmin = false;
        RegisterInput model = new RegisterInput();
        NewUserInput usr = new NewUserInput();
        SearchResultCollection results;
        string mobileNumber = string.Empty;
        using (DirectoryEntry domainEntry = new DirectoryEntry("LDAP://" + AppSettings.DomainName))
        {
            using (DirectorySearcher searcher = new DirectorySearcher(domainEntry, "userPrincipalName=" + userName + "@" + AppSettings.DomainName) { Filter = string.Format("(&(objectClass=user)(samaccountname={0}))", userName) })
            {
               results = searcher.FindAll();

                if (results.Count > 0)
                {
                    usr.FirstName = results[0].GetDirectoryEntry().Properties["givenName"].Value.ToString();
                    usr.LastName = results[0].GetDirectoryEntry().Properties["sn"].Value?.ToString();
                    usr.EmailAddress = results[0].GetDirectoryEntry().Properties["mail"].Value?.ToString();
                    mobileNumber = results[0].GetDirectoryEntry().Properties["mobile"]?.Value?.ToString();
                    dynamic userRoleList = results[0].GetDirectoryEntry().Properties["memberOf"];

                    if (userRoleList != null)
                    {
                        foreach (var role in userRoleList)
                        {
                            string[] split = role.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                            bool result = split.Any(x => x.ToLowerInvariant() == AppSettings.UserRole.ToLowerInvariant());
                            if (result)
                            {
                                isAdmin = true;
                                break;
                            }
                        }
                    }
                }
            }
        }

        model.NewUser = usr;