示例#1
0
        private Task <T> SearchForAsync <T>(string query, string[] attributes, Func <LdapEntry, T> mappingFunc) where T : class
        {
            if (string.IsNullOrEmpty(query))
            {
                throw new ArgumentException("Query cannot be null or empty", nameof(query));
            }

            if (!Regex.IsMatch(query, @"^[a-z][a-z0-9\\_]+$", RegexOptions.IgnoreCase))
            {
                _logger.LogInformation("Invalid characters in query {query}, returning null.", query);
                return(null);
            }

            LdapConfiguration configuration = GetLdapConfiguration();

            using LdapConnection connection = new LdapConnection();
            connection.Connect(configuration.Server, 389);
            connection.Bind(configuration.Username, configuration.Password);

            var searchResults = connection.Search(
                configuration.DistinguishedName,
                LdapConnection.ScopeSub,
                $"(&(objectCategory=person)(objectClass=user)(sAMAccountName={query}))",
                attributes,
                false);

            if (searchResults.HasMore())
            {
                LdapEntry entry = searchResults.Next();
                return(Task.FromResult(mappingFunc(entry)));
            }

            return(Task.FromResult((T)null)); // not found
        }
示例#2
0
        private LdapConfiguration GetLdapConfiguration()
        {
            var section = _configuration.GetSection("LDAP");

            var configuration = new LdapConfiguration
            {
                Server            = section["Server"],
                DistinguishedName = section["DistinguishedName"],
                Username          = section["Username"],
                Password          = section["Password"],
            };

            // TODO: check that all of these are configured, log error if they are not
            List <string> missingSettings = new List <string>();

            if (string.IsNullOrEmpty(configuration.Server))
            {
                missingSettings.Add(nameof(configuration.Server));
            }
            if (string.IsNullOrEmpty(configuration.DistinguishedName))
            {
                missingSettings.Add(nameof(configuration.DistinguishedName));
            }
            if (string.IsNullOrEmpty(configuration.Username))
            {
                missingSettings.Add(nameof(configuration.Username));
            }
            if (string.IsNullOrEmpty(configuration.Password))
            {
                missingSettings.Add(nameof(configuration.Password));
            }

            if (missingSettings.Count != 0)
            {
                string joinedSettings = string.Join(", ", missingSettings.ToArray());
                throw new ConfigurationErrorsException("Missing LDAP configuration settings: " + joinedSettings + ".");
            }

            return(configuration);
        }