服务器上的LDAP身份验证

时间:2013-09-16 15:24:40

标签: c# ldap directoryservices directoryentry

我需要使用输入用户名和密码在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块

  

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

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

请建议。

萨阿德建议, 我改变了代码

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 =新用户,OU = KK)

我正在使用servername,domain,admin username和password

创建目录条目

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

2 个答案:

答案 0 :(得分: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

        }
}

答案 1 :(得分: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;
    }
}