tags:

views:

291

answers:

2

I'm trying using LDAP to authenticate user, but I have a problem with LDAP.

This is my code:

string hostOrDomainName = "MrHand-PC";
string targetOu = "cn=Huy Pham,ou=people,dc=example,dc=com";

// create a search filter to find all objects
string ldapSearchFilter = "uid=pdhuy";

// establish a connection to the directory
LdapConnection connection = new LdapConnection(hostOrDomainName);

Console.WriteLine("\r\nPerforming a simple search ...");
SearchRequest searchRequest = new SearchRequest(targetOu, ldapSearchFilter, 
    System.DirectoryServices.Protocols.SearchScope.OneLevel, null);

// cast the returned directory response as a SearchResponse object
SearchResponse searchResponse =
            (SearchResponse)connection.SendRequest(searchRequest);

The last line throws an exception: The distinguished name contains invalid syntax.

Can anyone help my solve this problem?

A: 

To authenticate against LDAP, you can try the following (domain, username and password are arguments):

bool IsAuthenticated = false;            
string domainAndUsername = domain + @"\" + username;
string dirContext = GetAuthenticatingDirectory(domain);
using (DirectoryEntry entry = new DirectoryEntry("LDAP://" + dirContext, domainAndUsername, password))
{
    try
    {
        Object obj = entry.NativeObject;
        DirectorySearcher search = new DirectorySearcher(entry);
        search.Filter = "(SAMAccountName=" + username + ")";
        search.PropertiesToLoad.Add("cn");
        SearchResult result = search.FindOne();
        if (result != null)
        {
            IsAuthenticated = true;                            
        }
    }
    catch (Exception e)
    {
        //handle appropriately according to your requirements
    }
}

return IsAuthenticated;

where GetAuthenticatingDirectory() is defined as

private string GetAuthenticatingDirectory(string domain)
{
    string authenticatingDirectory = string.Empty;
    string dotComDomain = domain + @".com";

    // Connect to RootDSE
    using (DirectoryEntry RootDSE = new DirectoryEntry("LDAP://rootDSE"))
    {
        // Retrieve the Configuration Naming Context from RootDSE
        string configNC = RootDSE.Properties["configurationNamingContext"].Value.ToString();

        // Connect to the Configuration Naming Context
        using (DirectoryEntry configSearchRoot = new DirectoryEntry("LDAP://" + configNC))
        {
            // Search for all partitions where the NetBIOSName is set.
            using (DirectorySearcher configSearch = new DirectorySearcher(configSearchRoot))
            {
                configSearch.Filter = ("(NETBIOSName=*)");

                // Configure search to return dnsroot and ncname attributes
                configSearch.PropertiesToLoad.Add("dnsroot");
                configSearch.PropertiesToLoad.Add("ncname");
                using (SearchResultCollection forestPartitionList = configSearch.FindAll())
                {
                    // Loop through each returned domain in the result collection
                    foreach (SearchResult domainPartition in forestPartitionList)
                    {
                        // domainName like "domain.com". ncName like "DC=domain,DC=com"
                        string domainName = domainPartition.Properties["dnsroot"][0].ToString();
                        string ncName = domainPartition.Properties["ncname"][0].ToString();

                        if (dotComDomain.Equals(domainName, StringComparison.OrdinalIgnoreCase))
                        {
                            authenticatingDirectory = ncName;
                            break;
                        }
                    }
                }
            }
        }
    }

    return authenticatingDirectory;
}
Khnle
I tried your code and I got a error message: 'the directory service is unavailable'. Please help me solve this problem
handle0088
A: 

@Khnle: Now I know what problem I have

DirectoryEntry entry = new DirectoryEntry("LDAP://" + dirContext, domainAndUsername, password)

When I set AuthenticationType = AuthenticationTypes.Anonymous, everything is OK. But when AuthenticationType is Default, I get error message "the directory service is unavailable". Please tell me how to solve this problem? Thank you!

handle0088