public static void AssertSameAs(this LdapEntry expectedEntry, LdapEntry actualEntry)
        {
            Assert.Equal(expectedEntry.Dn, actualEntry.Dn);
            var expectedAttributes = expectedEntry.GetAttributeSet();
            var actualAttributes   = actualEntry.GetAttributeSet();

            expectedAttributes.AssertSameAs(actualAttributes);
        }
Example #2
0
        public UserViewModel Login(string username, string password)
        {
            // Creating an LdapConnection instance
            var ldapConn       = new LdapConnection();
            var tempDomainName = new StringBuilder(100);

            if (!string.IsNullOrEmpty(_settings.DomainName))
            {
                tempDomainName.Append(_settings.DomainName);
                tempDomainName.Append('\\');
            }

            tempDomainName.Append(username);
            //Connect function will create a socket connection to the server
            ldapConn.Connect(_settings.Address, _settings.PortNumber);

            //Bind function will Bind the user object Credentials to the Server
            ldapConn.Bind(tempDomainName.ToString(), password);


            var uservm = new UserViewModel()
            {
                UserName = username, Name = username
            };
            var cons = ldapConn.SearchConstraints;

            cons.ReferralFollowing = true;
            ldapConn.Constraints   = cons;

            var attributes = _settings.Attributes?.Trim() == "" ? null : _settings.Attributes?.Split(",").Select(s => s.Trim());
            var lsc        = ldapConn.Search(_settings.DistinguishedName,
                                             (int)Enum.Parse <SearchScope>(_settings.SearchScope),
                                             $"(sAMAccountName={username})",
                                             attributes?.ToArray(),
                                             false,
                                             (LdapSearchConstraints)null);

            while (lsc.HasMore())
            {
                LdapEntry nextEntry = null;
                nextEntry = lsc.Next();
                var attributeSet = nextEntry.GetAttributeSet();
                System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                while (ienum.MoveNext())
                {
                    var attribute     = (LdapAttribute)ienum.Current;
                    var attributeName = attribute.Name;
                    var attributeVal  = attribute.StringValue;

                    uservm.CustomClaims.Add(new Claim(attributeName, attributeVal));
                }
            }

            return(uservm);
        }
Example #3
0
        private LdapAttribute GetAttribute(LdapEntry userEntry, string attr)
        {
            var attributeSet = userEntry.GetAttributeSet();

            if (attributeSet.ContainsKey(attr))
            {
                return(attributeSet.GetAttribute(attr));
            }

            _logger.LogWarning("LDAP attribute {Attr} not found for user {User}", attr, userEntry.Dn);
            return(null);
        }
Example #4
0
        // Obtains an email address, given an employee ID.
        public string EmailByEmployeeId(string employeeId)
        {
            // If the OverrideEmail config setting is set to a string, then
            // we just return it. It will be the user email instead of looking
            // up their email.
            if (!string.IsNullOrWhiteSpace(OverrideEmail))
            {
                return(OverrideEmail);
            }

            // Otherwise, continue on, using the LDAP connection to filter by
            // the employee ID and find the user's mail (email) attribute.
            using (var ldapConnection = new LdapConnection())
            {
                ldapConnection.Connect(Host, Port);
                ldapConnection.Bind(Username, Password);

                ILdapSearchResults results = ldapConnection.Search(
                    Base,
                    LdapConnection.ScopeSub,
                    $"(employeeID={employeeId})",
                    new string[] { "mail" },
                    false
                    );

                while (results.HasMore())
                {
                    LdapEntry        nextEntry           = results.Next();
                    LdapAttributeSet attributes          = nextEntry.GetAttributeSet();
                    System.Collections.IEnumerator ienum = attributes.GetEnumerator();

                    // Parse through the attribute set to get the attributes and the
                    // corresponding values
                    while (ienum.MoveNext())
                    {
                        LdapAttribute attribute     = (LdapAttribute)ienum.Current;
                        string        attributeName = attribute.Name;
                        string        attributeVal  = attribute.StringValue;

                        if (attributeName == "mail")
                        {
                            // Success. Return the mail attribute value, which
                            // is the user's email address.
                            return(attributeVal);
                        }
                    }
                }

                // Return blank if we don't find an email for that employee.
                return("");
            }
        }
Example #5
0
        public static IList <LdapAttribute> GetLdapEntryAttributes(this LdapEntry entry)
        {
            IList <LdapAttribute> attributes = new List <LdapAttribute>();

            LdapAttributeSet attributeSet = entry.GetAttributeSet();

            System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
            while (ienum.MoveNext())
            {
                LdapAttribute attribute = (LdapAttribute)ienum.Current;
                attributes.Add(attribute);
            }

            return(attributes);
        }
Example #6
0
        // Replace this method with custom entity mapper.
        private static Employee ToEmployee([NotNull] LdapEntry entry)
        {
            if (entry == null)
            {
                throw new ArgumentNullException(nameof(entry));
            }

            var employee   = new Employee();
            var attributes = entry.GetAttributeSet();

            foreach (LdapAttribute attribute in attributes)
            {
                if (attribute.Name == "sAMAccountName")
                {
                    employee.Login = attribute.StringValue;
                }

                // toDo: handle multivalued attributes (just grab them all with)
                switch (attribute.Name)
                {
                case "sAMAccountName":
                    employee.Login = attribute.StringValue;
                    break;

                case "givenName":
                    employee.Name = attribute.StringValue;
                    break;

                case "sn":
                    employee.Surname = attribute.StringValue;
                    break;

                case "initials":
                    employee.Initials = attribute.StringValue;
                    break;

                case "department":
                    employee.Department = attribute.StringValue;
                    break;

                default:
                    Debug.WriteLine($"Unexpected attribute: <{attribute.Name}>");
                    break;
                }
            }

            return(employee);
        }
Example #7
0
        private User MapSearchResult(LdapEntry entry)
        {
            LdapAttributeSet attributeSet = entry.GetAttributeSet();

            var user = new User
            {
                Id                = GetValueOrDefault(attributeSet, "bcgovGUID"),
                UserName          = GetValueOrDefault(attributeSet, "sAMAccountName"),
                FirstName         = GetValueOrDefault(attributeSet, "givenName"),
                LastName          = GetValueOrDefault(attributeSet, "sn"),
                Email             = GetValueOrDefault(attributeSet, "mail"),
                UserPrincipalName = GetValueOrDefault(attributeSet, "userPrincipalName")
            };

            return(user);
        }
Example #8
0
 private string GetAttributeValue(LdapEntry entity, string attributeKey)
 {
     if (!String.IsNullOrEmpty(attributeKey))
     {
         var entityAttributes = entity.GetAttributeSet();
         if (entityAttributes.ContainsKey(attributeKey))
         {
             var attrValue = entity.GetAttribute(attributeKey);
             if (attrValue != null && !String.IsNullOrEmpty(attrValue.StringValue))
             {
                 return(attrValue.StringValue);
             }
         }
     }
     return(null);
 }
        public User Login(string userName, string password)
        {
            User user = new User();


            using (var cn = new Novell.Directory.Ldap.LdapConnection())
            {
                cn.Connect(config.Path, config.Port);

                try
                {
                    cn.Bind(config.UserDomainName + "\\" + userName, password);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine("Failed login attempt for user " + userName);
                    user = null;
                    return(user);
                }

                string filter = "sAMAccountname=" + userName;

                string baseStr = "OU=BLS,DC=blacklanternsecurity,DC=com";

                LdapSearchResults result = (LdapSearchResults)cn.Search(baseStr, LdapConnection.ScopeSub, filter, null, false);

                LdapEntry entry = null;
                try
                {
                    entry = result.First();
                }
                catch (LdapException e)
                {
                    Console.WriteLine("Error: " + e.LdapErrorMessage);
                }

                LdapAttributeSet attributeSet = entry.GetAttributeSet();

                user.DisplayName = attributeSet.GetAttribute("displayName").StringValue;
                user.GivenName   = attributeSet.GetAttribute("givenName").StringValue;
                user.UserName    = userName;

                return(user);
            }
        }
        private static bool Enabled(LdapEntry entry, ParameterAccessor.Parts.Ldap ldap)
        {
            var accountDisabled = 2;

            if (!ldap.LdapExcludeAccountDisabled)
            {
                return(true);
            }
            if (entry.GetAttributeSet().Any(o => o.Key == "userAccountControl"))
            {
                var userAccountControl = entry.GetAttribute("userAccountControl")?.StringValue;
                return(userAccountControl.IsNullOrEmpty()
                    ? true
                    : (userAccountControl.ToLong() & accountDisabled) == 0);
            }
            else
            {
                return(true);
            }
        }
        public LdapConnectionResult Test(string username, string password)
        {
            // Creating an LdapConnection instance
            var ldapConn       = new LdapConnection();
            var tempDomainName = new StringBuilder(100);

            if (!string.IsNullOrEmpty(_settings.DomainName))
            {
                tempDomainName.Append(_settings.DomainName);
                tempDomainName.Append('\\');
            }

            tempDomainName.Append(username);
            try
            {
                //Connect function will create a socket connection to the server
                ldapConn.Connect(_settings.Address, _settings.PortNumber);

                //Bind function will Bind the user object Credentials to the Server
                ldapConn.Bind(tempDomainName.ToString(), password);
            }
            catch (Exception e)
            {
                return(new LdapConnectionResult(false, e.Message, "Login"));
            }

            // Searches in the Marketing container and return all child entries just below this
            //container i.e. Single level search

            var claims = new List <ClaimViewModel>();

            try
            {
                var cons = ldapConn.SearchConstraints;
                cons.ReferralFollowing = true;
                ldapConn.Constraints   = cons;

                var attributes = _settings.Attributes?.Trim() == "" ? null : _settings.Attributes?.Split(",").Select(s => s.Trim());
                var lsc        = ldapConn.Search(_settings.DistinguishedName,
                                                 (int)Enum.Parse <SearchScope>(_settings.SearchScope),
                                                 $"(sAMAccountName={username})",
                                                 attributes?.ToArray(),
                                                 false,
                                                 (LdapSearchConstraints)null);

                while (lsc.HasMore())
                {
                    LdapEntry nextEntry = null;
                    try
                    {
                        nextEntry = lsc.Next();
                    }
                    catch (LdapException e)
                    {
                        ldapConn.Disconnect();
                        return(new LdapConnectionResult(false, e.Message, "Search Error"));
                    }
                    var attributeSet = nextEntry.GetAttributeSet();
                    System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                    while (ienum.MoveNext())
                    {
                        var attribute     = (LdapAttribute)ienum.Current;
                        var attributeName = attribute.Name;
                        var attributeVal  = attribute.StringValue;

                        claims.Add(new ClaimViewModel(attributeName, attributeVal));
                    }
                }
            }
            catch (Exception e)
            {
                ldapConn.Disconnect();
                return(new LdapConnectionResult(false, e.Message, "Search Error"));
            }

            ldapConn.Disconnect();
            return(new LdapConnectionResult(true, claims.OrderBy(b => b.Type).ToList()));
        }
Example #12
0
        public static void UserList(string objectDN, string password, string searchBase)
        {
            LdapConnection conn = new LdapConnection();

            try
            {
                Console.WriteLine("Connecting to " + ldapHost);
                // Connect to the LDAP server using the host and the port
                // ldap//<host>:<port>
                conn.Connect(ldapHost, ldapPort);
                conn.Bind(objectDN, password);

                string[] requiredAttributes = { "cn", "sn", "uid", "userPassword" };
                string   searchFilter       = "objectClass=inetOrgPerson";

                ILdapSearchResults lsc = conn.Search(searchBase,
                                                     LdapConnection.ScopeSub,
                                                     searchFilter,
                                                     requiredAttributes,
                                                     false);

                while (lsc.HasMore())
                {
                    LdapEntry nextEntry = null;

                    try
                    {
                        nextEntry = lsc.Next();
                    }
                    catch (LdapException e)
                    {
                        Console.WriteLine("Error : " + e.LdapErrorMessage);
                        continue;
                    }

                    Console.WriteLine("\n" + nextEntry.Dn);
                    LdapAttributeSet attributeSet = nextEntry.GetAttributeSet();
                    IEnumerator      ienum        = attributeSet.GetEnumerator();

                    while (ienum.MoveNext())
                    {
                        LdapAttribute attribute     = (LdapAttribute)ienum.Current;
                        string        attributeName = attribute.Name;
                        string        attributeVal  = attribute.StringValue;
                        Console.WriteLine("\t" + attributeName + "\tvalue = \t" + attributeVal);
                    }
                }

                conn.Disconnect();
            }
            catch (LdapException e)
            {
                Console.WriteLine("Error: " + e.LdapErrorMessage);
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
                return;
            }
            finally
            {
                conn.Disconnect();
            }
        }
Example #13
0
        public GxSimpleCollection <string> GetAttribute(string name, string context, GXProperties atts)
        {
            string filter = "";

            if (atts.Count == 0)
            {
                filter = "(" + name + "=*)";
            }
            else
            {
                for (int i = 0; i < atts.Count; i++)
                {
                    filter += "(" + atts.GetKey(i).Trim() + "=" + atts[i].Trim() + ")";
                }
                if (atts.Count > 1)
                {
                    filter = "(&" + filter + ")";
                }
            }
            GxSimpleCollection <string> sc = new GxSimpleCollection <string>();

            try
            {
#if NETCORE
                if (!GXUtil.IsWindowsPlatform)
                {
                    NovellConnect();

                    string             searchBase   = context;
                    int                searchScope  = LdapConnection.ScopeSub;
                    string             searchFilter = filter;
                    ILdapSearchResults lsc          = _conn.Search(searchBase, searchScope, searchFilter, new string[] { name }, false);

                    while (lsc.HasMore())
                    {
                        LdapEntry nextEntry = null;
                        try
                        {
                            nextEntry = lsc.Next();
                        }
                        catch (LdapException)
                        {
                            continue;
                        }
                        LdapAttributeSet attributeSet = nextEntry.GetAttributeSet();
                        IEnumerator      ienum        = attributeSet.GetEnumerator();
                        StringBuilder    sb           = new StringBuilder();
                        while (ienum.MoveNext())
                        {
                            LdapAttribute attribute    = (LdapAttribute)ienum.Current;
                            string        attributeVal = attribute.StringValue;
                            sb.Append(attributeVal + " ");
                        }
                        sc.Add(sb.ToString() + " ");
                    }
                }
                else
#endif
                {
                    if (_entry != null)
                    {
                        _entry.Close();
                        _entry = null;
                    }
                    string context1;
                    if (context.Trim().Length == 0)
                    {
                        context1 = "";
                    }
                    else
                    {
                        context1 = "/" + context;
                    }
                    AuthenticationTypes at = getAuthentication();
                    _entry = new DirectoryEntry("LDAP://" + getPath() + context1, _user, _password, at);
                    DirectorySearcher ds = new DirectorySearcher(_entry, filter, new string[] { name });
                    foreach (SearchResult result in ds.FindAll())
                    {
                        PropertyValueCollection values = (PropertyValueCollection)(result.GetDirectoryEntry().Properties[name]);
                        StringBuilder           sb     = new StringBuilder();
                        for (int i = 0; i < values.Count; i++)
                        {
                            sb.Append(values[i].ToString() + " ");
                        }
                        sc.Add(sb.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                GXLogging.Error(log, "GetAttribute Method Error.", ex);
            }
            return(sc);
        }
Example #14
0
        public static Task <bool> LoginAsync(string username, string password)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            CancellationToken       cancellationToken = cts.Token;

            LdapConnection conn = null;


            return(Task.Factory.StartNew(() => {
                conn = new LdapConnection();
                conn.Connect(Host, Port);


                if (!string.IsNullOrEmpty(username))
                {
                    try
                    {
                        conn.Bind(dn, pa);
                    }
                    catch (Exception e)
                    {
                        conn.Disconnect();
                        return false;
                    }

                    string searchBase = filter;

                    int searchScope = LdapConnection.ScopeSub;
                    string searchFilter = "uid=" + username.Trim();
                    LdapSearchQueue queue = conn.Search(searchBase,
                                                        searchScope,
                                                        searchFilter,
                                                        null,
                                                        false,
                                                        (LdapSearchQueue)null,
                                                        (LdapSearchConstraints)null);

                    LdapMessage message;
                    while ((message = queue.GetResponse()) != null)
                    {
                        try
                        {
                            string msg = message.ToString();

                            LdapEntry entry = ((LdapSearchResult)message).Entry;

                            LdapAttributeSet attributeSet = entry.GetAttributeSet();
                            System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();

                            LdapAttribute cn = attributeSet.GetAttribute("cn");
                            string idUser = cn.StringValue;

                            try
                            {
                                conn.Bind("cn=" + idUser + "," + filter, password);
                            }
                            catch (Exception e)
                            {
                                conn.Disconnect();
                                return false;
                            }

                            conn.Disconnect();
                            return true;
                        }
                        catch (Exception e)
                        {
                            conn.Disconnect();
                            return false;
                        }
                    }
                }

                return false;
            }, cancellationToken));
        }
Example #15
0
        public static Task <bool> ModifyAsync(string oldUsername, string username, string password, string nombre, string apellido, string email)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            CancellationToken       cancellationToken = cts.Token;

            LdapConnection conn = null;


            return(Task.Factory.StartNew(() => {
                conn = new LdapConnection();
                conn.Connect(Host, Port);

                if (!string.IsNullOrEmpty(username))
                {
                    try
                    {
                        conn.Bind(dn, pa);
                    }
                    catch (Exception e)
                    {
                        conn.Disconnect();
                        return false;
                    }

                    string searchBase = filter;

                    int searchScope = LdapConnection.ScopeSub;
                    string searchFilter = "uid=" + username.Trim();
                    LdapSearchQueue queue = conn.Search(searchBase,
                                                        searchScope,
                                                        searchFilter,
                                                        null,
                                                        false,
                                                        (LdapSearchQueue)null,
                                                        (LdapSearchConstraints)null);

                    LdapMessage message;
                    while ((message = queue.GetResponse()) != null)
                    {
                        try
                        {
                            string msg = message.ToString();

                            LdapEntry entry = ((LdapSearchResult)message).Entry;

                            LdapAttributeSet attributeSet = entry.GetAttributeSet();
                            System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();

                            LdapAttribute cn = attributeSet.GetAttribute("cn");
                            string idUser = cn.StringValue;

                            try
                            {
                                conn.Delete("cn=" + idUser + "," + filter);


                                LdapAttributeSet ldapAttributeSet = new LdapAttributeSet();
                                ldapAttributeSet.Add(new LdapAttribute("cn", nombre + " " + apellido));
                                ldapAttributeSet.Add(new LdapAttribute("sn", username));
                                ldapAttributeSet.Add(new LdapAttribute("homeDirectory", "/home/users/" + username));
                                ldapAttributeSet.Add(new LdapAttribute("objectClass", new string[] { "inetOrgPerson", "posixAccount", "top" }));
                                ldapAttributeSet.Add(new LdapAttribute("uid", username));
                                ldapAttributeSet.Add(new LdapAttribute("givenName", nombre));
                                ldapAttributeSet.Add(new LdapAttribute("uidNumber", "1000"));
                                ldapAttributeSet.Add(new LdapAttribute("gidNumber", "500"));
                                ldapAttributeSet.Add(new LdapAttribute("mail", email));
                                ldapAttributeSet.Add(new LdapAttribute("userPassword", password));

                                LdapEntry ldapEntry = new LdapEntry("cn=" + nombre + " " + apellido + "," + filter, ldapAttributeSet);

                                conn.Add(ldapEntry);
                            }
                            catch (Exception e)
                            {
                                conn.Disconnect();
                                return false;
                            }

                            conn.Disconnect();
                            return true;
                        }
                        catch (Exception e)
                        {
                            conn.Disconnect();
                            return false;
                        }
                    }
                }

                return false;
            }, cancellationToken));
        }
        public ApiResultAd?GetUserInfo(string username, string pw)
        {
            _logger.Information("START Novell.Directory.Ldap.LdapPasswordChangeProvider.GetUserInfo");
            var result = new ApiResultAd();

            try
            {
                var cleanUsername = CleaningUsername(username);
                _logger.Information("Zyborg.PerformPasswordChange: cleanUsername="******"{Username}", cleanUsername);
                _logger.Information("Zyborg.PerformPasswordChange: searchFilter=" + searchFilter);

                _logger.Warning("LDAP query: {0}", searchFilter);

                using var ldap = BindToLdap();
                var search = ldap.Search(
                    _options.LdapSearchBase,
                    LdapConnection.ScopeSub,
                    searchFilter,
                    new[] { "distinguishedName" },
                    false,
                    _searchConstraints);

                // We cannot use search.Count here -- apparently it does not
                // wait for the results to return before resolving the count
                // but fortunately hasMore seems to block until final result
                if (!search.HasMore())
                {
                    _logger.Warning("Unable to find username: [{0}]", cleanUsername);

                    //result.Errors = new ApiErrorItem(ApiErrorCode.InvalidCredentials, "Mật khẩu không đúng!");
                    result.Errors = new ApiErrorItem(_options.HideUserNotFound ? ApiErrorCode.InvalidCredentials : ApiErrorCode.UserNotFound,
                                                     _options.HideUserNotFound ? "Invalid credentials" : "Username could not be located");

                    return(result);
                }

                if (search.Count > 1)
                {
                    _logger.Warning("Found multiple with same username: [{0}] - Count {1}", cleanUsername, search.Count);

                    // Hopefully this should not ever happen if AD is preserving SAM Account Name
                    // uniqueness constraint, but just in case, handling this corner case
                    result.Errors = new ApiErrorItem(ApiErrorCode.UserNotFound, "Multiple matching user entries resolved");
                    return(result);
                }

                var userDN = search.Next().Dn;
                while (search.HasMore())
                {
                    LdapEntry nextEntry = null;
                    try
                    {
                        nextEntry = search.Next();
                    }
                    catch (LdapException e)
                    {
                        _logger.Error("Error: " + e.LdapErrorMessage);
                        //Console.WriteLine("Error: " + e.LdapErrorMessage);
                        // Exception is thrown, go for next entry
                        continue;
                    }
                    _logger.Warning("==>User: "******"\n" + nextEntry.Dn);
                    LdapAttributeSet attributeSet        = nextEntry.GetAttributeSet();
                    System.Collections.IEnumerator ienum = attributeSet.GetEnumerator();
                    while (ienum.MoveNext())
                    {
                        LdapAttribute attribute     = (LdapAttribute)ienum.Current;
                        string        attributeName = attribute.Name;
                        string        attributeVal  = attribute.StringValue;
                        _logger.Warning(attributeName + " value:" + attributeVal);
                        //Console.WriteLine(attributeName + "value:" + attributeVal);
                    }
                }

                //LdapAttributeSet attributeSet = new LdapAttributeSet();
                //attributeSet.GetAttribute("");

                if (_options.LdapStartTls)
                {
                    ldap.StopTls();
                }

                ldap.Disconnect();
            }
            catch (LdapException ex)
            {
                result.Errors = ParseLdapException(ex);

                _logger.Warning(ex.Message);

                return(result);
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
            {
                result.Errors = ex is ApiErrorException apiError
                    ? apiError.ToApiErrorItem()
                    : new ApiErrorItem(ApiErrorCode.InvalidCredentials, $"Failed to update password: {ex.Message}");

                _logger.Warning(ex.Message);

                return(result);
            }

            // Everything seems to have worked:
            return(null);
        }
Example #17
0
        public LdapLogin(LdapConfiguration config, string username, string password)
        {
            this.TimeoutSeconds = config.TimeoutSeconds;

            using (var cn = new LdapConnection())
            {
                // connect
                try
                {
                    string server = string.IsNullOrWhiteSpace(config.Server) ? config.Domain : config.Server;

                    cn.Connect(server, config.Port);
                    // bind with an username and password
                    // this how you can verify the password of an user
                    cn.Bind(config.BindUser, config.BindPassword);

                    string searchBase   = config.SearchBase;
                    string searchFilter = string.Empty;
                    if (username.Contains("@"))
                    {
                        searchFilter = $"(userPrincipalName=" + username + ")";
                    }
                    else
                    {
                        searchFilter = $"(samaccountname=" + username + ")";
                    }

                    string[] attrs = new string[] { "cn", "userPrincipalName", "givenname", "samaccountname",
                                                    "displayname", "givenName", "sn", "objectSid", "memberOf" };

                    try
                    {
                        ILdapSearchResults results = cn.Search(config.SearchBase, LdapConnection.ScopeSub,
                                                               searchFilter, attrs, false);
                        string[] groups = null;

                        while (results.HasMore())
                        {
                            LdapEntry nextEntry = null;
                            try
                            {
                                nextEntry = results.Next();
                            }
                            catch
                            {
                                continue;
                            }

                            // Get the attribute set of the entry
                            LdapAttributeSet attributeSet = nextEntry.GetAttributeSet();

                            this.CN        = attributeSet.GetAttribute("cn")?.StringValue;
                            this.ID        = attributeSet.GetAttribute("objectSid")?.StringValue;
                            this.GivenName = attributeSet.GetAttribute("givenname")?.StringValue;
                            this.Surname   = attributeSet.GetAttribute("sn")?.StringValue;
                            this.Name      = attributeSet.GetAttribute("displayname")?.StringValue;
                            groups         = attributeSet.GetAttribute("memberOf")?.StringValueArray;

                            if (groups != null)
                            {
                                foreach (string group in groups)
                                {
                                    if (group.Equals(config.AdminGroupDN, StringComparison.OrdinalIgnoreCase))
                                    {
                                        this.IsAdmin = true;
                                    }
                                    if (group.Equals(config.UserGroupDN, StringComparison.OrdinalIgnoreCase))
                                    {
                                        this.IsUser = true;
                                    }
                                }
                            }
                        }

                        cn.Bind(this.CN, password);

                        this.IsAuthenticated = true;
                        cn.Disconnect();
                    }
                    catch
                    {
                        this.IsAuthenticated = false;
                        return;
                    }
                }
                catch
                {
                    this.IsAuthenticated = false;
                }
            }
        }