[英]C# failed to load right user attribute in LDAP
我無法使用以下代碼從 LDAP 檢索正確的用戶屬性:
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();
}
例如,我想獲取名為 Albert Einstein 的用戶的屬性,但無論我輸入什么用戶名,我總是得到 Isaac Newton 的屬性
我正在使用這個參考: How to find a User's Group with LDAP in C# Core 2
我正在使用 ForumSYS 的公共 LDAP 服務器,對於域它應該是ldap.forumsys.com
和端口是389
當您說“無論我輸入什么用戶名”時,您指的是txtUsername.Text
嗎? 因為您僅使用它進行身份驗證,而不是搜索。 您正在搜索目錄中的每個用戶,因為您將過濾器設置為(objectclass=person)
。
如果您只想查找一位用戶,則將過濾器設置為僅查找該一位用戶。 例如:
string searchFilter = "(cn=Albert Einstein)";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.