Verify if password is correct

梦想的初衷 提交于 2020-03-05 19:43:13

问题


i need to verify if the password is correct for a user.

i have this code:

 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;
        }
    }

but then directory searcher is not supported with WinNt, so i found another way to loop through all records.

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

but this just gets the name and doesnt verify the password.

please help . thanks


回答1:


To autenticate against LDAP or WinNT, you need no DirectorySearcher. You only need to get the NativeObject from your DirectoryEntry instance. Here's a code sample that might guide you through the way.

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;
}

This code will return either a user is authentic or not. Once you can get the NativeObject property using this DirectoryEntry class instance, this means that the AD (or local computer) used impersonation to get this object. If you get the object without having a thrown exception, this means that the AD (or local computer) was able to authenticate the impersonnated user.

While you can use the currently authenticated user by specifying no username and password, but only the domain (or local computer), by specifying a username and password, you say you want to use impersonnation, so the security infrastructure will use the given username and password to try to retrieve the NativeObject property from this DirectoryEntry class instance.

To authenticate against the AD, just replace the "WinNT://" for "LDAP://".




回答2:


You can use DirectoryEntry itself.

See the example here: http://support.microsoft.com/kb/316748

Why are you using WinNT:// anyways?



来源:https://stackoverflow.com/questions/3934876/verify-if-password-is-correct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!