1

我需要验证用户的密码是否正确。

我有这个代码:

 private bool checkOldPasswordValid(string password, string username)
    {
        using (DirectoryEntry entry = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"))
        {
            entry.Username = username;
            entry.Password = password;

            DirectorySearcher searcher = new DirectorySearcher(entry);

            searcher.Filter = "(objectclass=user)";
            try
            {
                searcher.FindOne();
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }
    }

但是WinNt不支持目录搜索器,所以我找到了另一种遍历所有记录的方法。

 foreach (DirectoryEntry dc in entry.Children)
            {
                // prints the name
                System.Diagnostics.Debug.WriteLine(dc.Name);
            }

但这只是获取名称而不验证密码。

请帮忙 。谢谢

4

2 回答 2

3

要针对 LDAP 或 WinNT 进行身份验证,您不需要DirectorySearcher. 您只需NativeObject要从您的DirectoryEntry实例中获取。这是一个代码示例,可能会指导您完成整个过程。

public bool Authenticate(string username, string password, string domain) {
    bool authenticated = false;

    using (DirectoryEntry entry = new DirectoryEntry(@"WinNT://" + domain, username, password) {
        try {
            object nativeObject = entry.NativeObject;
            authenticated = true;
        } catch (DirectoryServicesCOMException ex) {
        }
    }

    return authenticated;
}

此代码将返回用户是否真实。一旦您可以使用此类实例获取 NativeObject 属性DirectoryEntry,这意味着 AD(或本地计算机)使用模拟来获取此对象。如果您在没有抛出异常的情况下获取对象,则这意味着 AD(或本地计算机)能够对模拟用户进行身份验证。

虽然您可以通过不指定用户名和密码,而只指定域(或本地计算机)来使用当前经过身份验证的用户,但通过指定用户名和密码,您表示要使用模拟,因此安全基础架构将使用给定的用户名和尝试从此类实例中检索NativeObject属性的密码。DirectoryEntry

要针对 AD 进行身份验证,只需替换"WinNT://"for "LDAP://"

于 2010-10-14T15:38:07.343 回答
2

您可以使用 DirectoryEntry 本身。

请参阅此处的示例:http: //support.microsoft.com/kb/316748

为什么你仍然使用 WinNT://?

于 2010-10-14T15:40:13.673 回答