1

我正在尝试使用我在 ADAM 中创建的用户对用户进行身份验证。但是,无论使用什么密码(正确或不正确),我的搜索都会返回一个有效的 DirectoryEntry 对象。我假设如果密码无效,那么搜索将返回一个空对象。我的假设是错误的还是下面的代码有缺陷?

DirectoryEntry de = new DirectoryEntry("LDAP://localhost:389/cn=Groups,cn=XXX,cn=YYY,dc=ZZZ");
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de;
deSearch.Filter = "(&(objectClass=user) (cn=" + userId + "))";
SearchResultCollection results = deSearch.FindAll();
if (results.Count > 0)
{
    DirectoryEntry d = new DirectoryEntry(results[0].Path, userId, password);
        if (d != null)
        DoSomething();

}
4

1 回答 1

0

您需要访问 DirectoryEntry 的属性以确定它是否有效。我通常检查 Guid 是否为空。

bool valid = false;
using (DirectoryEntry entry = new DirectoryEntry( results[0].Path, userId, password ))
{
     try
     {
         if (entry.Guid != null)
         {
            valid = true;
         }
     }
     catch (NullReferenceException) {}
}

注意:您还需要将搜索根目录条目和搜索器包装在using语句中,或者在完成后显式处理它们,以免资源处于使用状态。

PS我不确定当您尝试访问无效的目录条目属性时会引发哪个异常。一些实验可能是为了找出要捕获的异常。您不希望捕获所有异常,因为您可能希望以不同于身份验证失败的方式处理其他问题(例如,目录服务器不可用)。

于 2008-11-19T01:06:39.203 回答