1
votes

I need to authenticate LDAP user in c# with input username and password.

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();

And here I get the required record (could see the details) However when I try to authenticate it using below code, it always said authentication failure

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 
        }

    }
}

It always result in catch block with error message

Logon failure: unknown user name or bad password. failure: unknown user name or bad password.

I'm sure that the given password is correct.

Please suggest.

As suggest by Saad, I changed by code

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

Still it is giving error

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()

I think I am confused with which parameter to give where. I have LDAP server address something like 123.123.12.123 Domain Name like abc.com Admin username and password and Username and password which is needs be authenticated. (which is in OU=new users,OU=KK )

I am creating directory entry using servername, domain, admin username and password

How do I validate the username with given password?

2
to me its hard to tell, but im guessing most probably the search filter, have you tried browsing the LDAP Server via some app and making sure that you are looking in the right place? - Saad Alothman
I can see the record and its properties in debugging info like DirectoryEntry myuser = sr.GetDirectoryEntry(); Console.WriteLine("\r\n\r\nfound userName : " + myuser.Name); Console.WriteLine("\r\n department : " + (string)myuser.Properties["department"].Value ?? "<Undefined>"); So I think I have got correct record. - user1211476
Is it necessary to provide admin username and password for DirectoryEntry ? If we pass the current user credentials, will that be sufficient to validate the user against Active Directory { DirectoryEntry entry = new DirectoryEntry("LDAP://****.net/DC=***,DC=net", username, password, AuthenticationTypes.Secure); object nativeObject = entry.NativeObject; authenticated = true; } - Bh00shan

2 Answers

0
votes

This code works for me,try it and let me know (modify the filters and properties to suit your needs):

        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

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