简体   繁体   中英

C# failed to load right user attribute in LDAP

i'm not able to retrieve the right user attributes from LDAP using the code below:

        string login = "UID=" + txtUsername.Text + ",DC=example,DC=com";
        string password = txtPwd.Text;
        string domain = txtDomain.Text;
        int port = Convert.ToInt32(txtPort.Text);
        string searchBase = "DC=example,DC=com";
        string searchFilter = "(objectclass=person)";

        LdapConnection conn = new LdapConnection();

        try
        {
            conn.Connect(domain, port);
            conn.Bind(login, password); 

            HashSet<string> users = new HashSet<string>();
            LdapSearchResults searchResults = conn.Search(searchBase,
                                                LdapConnection.SCOPE_SUB,
                                                searchFilter,
                                                null,
                                                false);

            while (searchResults.hasMore())
            {
                var nextEntry = searchResults.next();
                nextEntry.getAttributeSet();
                var attr = nextEntry.getAttribute("cn");

                if (attr == null)
                {
                    users.Add(nextEntry.getAttribute("mail").StringValue);
                }
                else
                {
                    users.Add(attr.StringValue);
                }

                Session["Name"] = users.First();

                Response.Redirect("~/default.aspx");
            }
        }
        catch (LdapException ex)
        {
            lblErr.Visible = true;
            lblErr.Text = "Error authenticating: " + ex.LdapErrorMessage;
            return;
        }
        catch (Exception ex)
        {
            lblErr.Visible = true;
            lblErr.Text = "Error authenticating: " + ex.Message;
        }
        finally
        {
            conn.Disconnect();
        }

for example i want to get attributes of user named Albert Einstein but i always get attributes of Isaac Newton no matter what username i inputted

i'm using this reference: How to find a User's Group with LDAP in C# Core 2

i'm using ForumSYS's public LDAP server, for domain it should be ldap.forumsys.com and port is 389

When you say "no matter what username i inputted", are you referring to txtUsername.Text ? Because you're using that only to authenticate, not to search. You're searching for every user in the directory because you set the filter to (objectclass=person) .

If you only want to find one user, then set the filter to only find that one user. For example:

string searchFilter = "(cn=Albert Einstein)";

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