简体   繁体   中英

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;
        }


    }
}

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, eg

    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, ie

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

And add the user filter back later.

If you are having issues searching for entities in Active Directory, consider tools like ldp . You can use it to check your paths are correct, the object exists and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM