Reputation: 99
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
Upvotes: 0
Views: 211
Reputation: 40928
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)";
Upvotes: 1