1

我需要使用输入用户名和密码在 c# 中验证 LDAP 用户。

DirectoryEntry entry =
new DirectoryEntry("LDAP://" + ServerName + "/OU=managed users,OU=KK”, + LDAPDomain, AdminUsername, Adminpassword);

DirectorySearcher search = new DirectorySearcher(entry);
search.SearchScope = SearchScope.Subtree;
search.Filter = "(|(&(objectCategory=person)(objectClass=user)(name=" + inputUsername + ")))";
search.PropertiesToLoad.Add("cn");
var searchresult = search.FindAll();

在这里我得到了所需的记录(可以查看详细信息)但是当我尝试使用下面的代码对其进行身份验证时,它总是说身份验证失败

if (searchresult != null)
{
    foreach (SearchResult sr in searchresult)
    {
        DirectoryEntry myuser = sr.GetDirectoryEntry();
        myuser.Password = inputPassword;
        try
        {
            object nativeObject = myuser.NativeObject;
            if (nativeObject != null)
                isValid = true;
        }
        catch(excecption ex)
        {
            isValid = false;
            //Error message 
        }

    }
}

它总是导致带有错误消息的 catch 块

登录失败:未知用户名或密码错误。失败:未知用户名或密码错误。

我确定给定的密码是正确的。

请建议。

根据 Saad 的建议,我通过代码进行了更改

public static bool IsAuthenticated() 
{
    var isValid = false;
    string adServer = ConfigurationManager.AppSettings["Server"];
    string adDomain = ConfigurationManager.AppSettings["Domain"];
    string adminUsername = ConfigurationManager.AppSettings["AdminUsername"];
    string adminpassword = ConfigurationManager.AppSettings["Password"];
    string username = ConfigurationManager.AppSettings["Username"];
    string selection = ConfigurationManager.AppSettings["Selection"];
    string[] dc = adDomain.Split('.');
    string dcAdDomain = string.Empty;

    foreach (string item in dc)
    {
        if (dc[dc.Length - 1].Equals(item))
            dcAdDomain = dcAdDomain + "DC=" + item;
        else
            dcAdDomain = dcAdDomain + "DC=" + item + ",";
    }

    string domainAndUsername = dcAdDomain + @"\" + adminUsername;

    DirectoryEntry entry = new DirectoryEntry("LDAP://" + adServer, domainAndUsername, adminpassword);

    try
    {                
        //Bind to the native AdsObject to force authentication.
        object obj = entry.NativeObject;             
        DirectorySearcher search = new DirectorySearcher(entry);

        search.Filter = "(SAMAccountName=" + username + ")";
        search.PropertiesToLoad.Add("cn");
        SearchResult result = search.FindOne();
        Console.WriteLine("And here is the result = " + result);
        if (null == result)
        {
            isValid = false;
        }

        //Update the new path to the user in the directory.
        var _path1 = result.Path;
        var _filterAttribute = (string)result.Properties["cn"][0];
        Console.WriteLine("And here is the _path1 = " + _path1);
        Console.WriteLine("And here is the _filterAttribute = " + _filterAttribute);
        isValid = true;
    }
    catch (Exception ex1)
    {// your catch here
        Console.WriteLine("Exception occurred " + ex1.Message + ex1.StackTrace);
    }
    return isValid;
}

它仍然给出错误

Exception occurred Logon failure: unknown user name or bad passwor
d.
   at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
   at System.DirectoryServices.DirectoryEntry.Bind()
   at System.DirectoryServices.DirectoryEntry.get_NativeObject()
   at Portal.LdapTest.Program.IsAuthenticated()

我想我对在哪里给出哪个参数感到困惑。我有 LDAP 服务器地址,例如 123.123.12.123 域名,例如 abc.com 管理员用户名和密码 以及 需要验证的用户名和密码。(在 OU=new users,OU=KK 中)

我正在使用服务器名、域、管理员用户名和密码创建目录条目

如何使用给定的密码验证用户名?

4

2 回答 2

0
public bool AuthenticateUser(string EmailAddress, string password,out string msg)
{
    msg = string.Empty;

    if (password == null || password == string.Empty || EmailAddress == null || EmailAddress == string.Empty)
    {
        msg = "Email and/or password can't be empty!";
        return false;
    }

    try
    {
        ADUserInfo userInfo = GetUserAttributes(EmailAddress);

        if (userInfo == null)
        {
            msg = "Error: Couldn't fetch user information!";
            return false;
        }
        DirectoryEntry directoryEntry = new DirectoryEntry(LocalGCUri, userInfo.Upn, password);
        directoryEntry.AuthenticationType = AuthenticationTypes.None;
        string localFilter = string.Format(ADSearchFilter, EmailAddress);


        DirectorySearcher localSearcher = new DirectorySearcher(directoryEntry);
        localSearcher.PropertiesToLoad.Add("mail");
        localSearcher.Filter = localFilter;

        SearchResult result = localSearcher.FindOne();


        if (result != null)
        {
            msg = "You have logged in successfully!";
            return true;
        }
        else
        {
            msg = "Login failed, please try again.";
            return false;
        }
    }catch (Exception ex)
    {
        //System.ArgumentException argEx = new System.ArgumentException("Logon failure: unknown user name or bad password");
        //throw argEx;
        msg = "Wrong Email and/or Password!";
        return false;
    }
}
于 2013-09-24T12:39:10.850 回答
0

此代码对我有用,请尝试并让我知道(修改过滤器和属性以满足您的需要):

        public bool IsAuthenticated(string domain, string username, string pwd){
        string domainAndUsername = domain + @"\" + username;
        DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);

        try
        {

                //Bind to the native AdsObject to force authentication.
                object obj = entry.NativeObject;

                DirectorySearcher search = new DirectorySearcher(entry);

                search.Filter = "(SAMAccountName=" + username + ")";
                search.PropertiesToLoad.Add("cn");
                SearchResult result = search.FindOne();

                if (null == result)
                {
                    return false;
                }

                //Update the new path to the user in the directory.
                _path = result.Path;
                _filterAttribute = (string)result.Properties["cn"][0];

        }
        catch(Exception e){// your catch here

        }
}
于 2013-09-17T09:28:52.460 回答