0

I am trying to validate a user using a secured LDAP query. My code throws an exception while calling

SearchResult result = search.FindOne;

code:

public LDAPDto LDAPLogin1(string userName, string mima)
    {
        string domainName = System.Configuration.ConfigurationManager.AppSettings["LDAPDomainName"];
        string _path = System.Configuration.ConfigurationManager.AppSettings["LDAPPath"];
        PrincipalContext ADCHECK = null;
        try
        {
            ADCHECK = new PrincipalContext(ContextType.Domain, domainName);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        if (!ADCHECK.ValidateCredentials(userName, mima, ContextOptions.Negotiate))
        {
            return new LDAPDto() { IsLogin = false };
        }
        string domainAndUsername = domainName + @"\" + userName;
        DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, mima);
        DirectorySearcher search = null;
        try
        {
            search = new DirectorySearcher(entry);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        try
        {
            search.Filter = "(SAMAccountName=" + userName + ")";
        }
        catch (Exception ex)
        {
            throw ex;
        }
        search.PropertiesToLoad.AddRange(new string[] { "sn", "givenName", "displayName", "title", "department" });
        SearchResult result;
        try
        {
            result = search.FindOne();
            result.GetDirectoryEntry();
        }
        catch (Exception ex)
        {
            //there throw ex
            throw ex;
        }
        var user = new LDAPDto()
        {
            IsLogin = true,
            Img = null,
            Sn = (string)result.Properties["sn"][0],
            Title = (string)result.Properties["title"][0],
            GivenName = (string)result.Properties["givenName"][0],
            DisplayName = (string)result.Properties["displayName"][0],
            Department = (string)result.Properties["department"][0],
        };
        return user;
    }

but I don't understand if(My AD had set : "sn", "givenName", "displayName", "title", "department" those value ,and it can work, other ad member just set "sn", "givenName", "displayName" / "title", "department" is null and i got fail)

does any resan i got fail ?

ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index.

Howard
  • 79
  • 1
  • 11
  • 1
    Add some info IF member1 AD had set ` { "sn" = "xxx", "givenName" ="xxx", "displayName"="xxx", "title"="xxxx", "department"="xxxxx"} ` – Howard Jul 29 '21 at 13:46

0 Answers0