Search code examples
c#asp-classicdirectoryservices

Not understanding LDAP DirectoryEntry Correctly


I am having some dramas with accessing LDAP using C# with my ASP project. It's a very simple example of just checking if a user exists within my directory service.

Here is the code. The function UserExists() is returning false

I'm not entirely sure if my LDAP query is even hitting my directory service. (Active Directory)

using System.DirectoryServices;

namespace UserManagement
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (UserExists("abc"))
                lblUserExists.Text = "Found Username";
        }

        public static DirectoryEntry GetDirectoryEntry()
        {
            DirectoryEntry de = new DirectoryEntry();
            de.Path = "LDAP://OU=Users,OU=Network Users,DC=domain,DC=org";
            de.AuthenticationType = AuthenticationTypes.Secure;

            return de;
        }

        public bool UserExists(String UserName)
        {
            DirectoryEntry de = GetDirectoryEntry();
            DirectorySearcher deSearch = new DirectorySearcher();

            deSearch.SearchRoot = de;
            deSearch.Filter = "(&(objectClass=user) (cn=" + UserName + "))";

            SearchResultCollection results = deSearch.FindAll();
            return results.Count > 0;
        }


    }
}

Solution

  • I'm no guru, but some ideas:

    1. LDAP connection string doesn't look right - I would have thought it would look more like LDAP://MyADServer:389/CN=SomeStore,OU=Users,OU=Network Users,DC=domain,DC=org

    2. You might need some properties to load, e.g.

      string[] propertiesToLoad = new string[] { "DistinguishedName", "mail" } ; ... deSearch.PropertiesToLoad = propertiesToLoad;

    3. Possibly try fetch data without the username filter first to see if the connection works, i.e.

      deSearch.Filter = "(&(objectClass=user))"

    And add the user filter back later.