コード例 #1
0
        public static List <T> ConvertLdapResult <T>(ILogger logger, ILdapSearchResults result, IEnumerable <int> employeeIds, Func <string, LdapAttribute, object> retrieveValue = null)
        {
            var ret = new List <T>();

            while (result.HasMore())
            {
                if (result.Count > 0)
                {
                    var nextEntry = result.Next();
                    try
                    {
                        var empid = nextEntry.GetAttribute("initials").StringValue;
                        if (employeeIds != null)
                        {
                            if (employeeIds.Contains(Convert.ToInt32(empid)))
                            {
                                var x = ConvertLdapEntry <T>(logger, nextEntry, retrieveValue);
                                ret.Add(x);
                            }
                        }
                        else
                        {
                            var x = ConvertLdapEntry <T>(logger, nextEntry, retrieveValue);
                            ret.Add(x);
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.LogError($"Error getting intials atribute: {ex.Message}");
                    }
                }
            }

            return(ret);
        }
コード例 #2
0
        public static Dictionary <string, IList <LdapAttribute> > GetAllLdapEntries(this ILdapSearchResults searchResult)
        {
            Dictionary <string, IList <LdapAttribute> > entryList = new Dictionary <string, IList <LdapAttribute> >();

            while (searchResult.HasMore())
            {
                var entry = searchResult.Next();

                entryList.Add(entry.Dn, entry.GetLdapEntryAttributes());
            }
            return(entryList);
        }
コード例 #3
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("");
            }
        }
        async Task <IList <LdapEntry> > Search(string filter)
        {
            return(await Task.Run(() =>
            {
                ILdapSearchResults results = Connection.Search(
                    configuration["Ldap:Root"],
                    LdapConnection.ScopeSub,
                    filter,
                    Attributes,
                    false,
                    (LdapSearchConstraints)null); // TODO: adjust LdapSearchConstraints

                List <LdapEntry> entries = results.Where(e => null != e).ToList();
                return entries.AsReadOnly();
            }));
        }
コード例 #5
0
        private static string ConnectionDescriptor(string directoryServer, int directoryServerPort, string defaultAdminContext, string serviceName)
        {
            var key = serviceName + defaultAdminContext;

            if (cache.ContainsKey(key))
            {
                TimeSpan difference = DateTime.Now - cache[key].Item1;
                if (difference.TotalSeconds < cacheExpiration)
                {
                    return(cache[key].Item2);
                }
                else
                {
                    cache.Remove(key);
                }
            }

            try
            {
                LdapConnection conn = new LdapConnection();
                conn.Connect(directoryServer, directoryServerPort);
                conn.Bind(defaultAdminContext, "");
                ILdapSearchResults searchResults = conn.Search(defaultAdminContext,
                                                               LdapConnection.ScopeSub, string.Format("(&(objectclass=orclNetService)(cn={0}))", serviceName), null, false);

                while (searchResults.HasMore())
                {
                    var nextEntry = searchResults.Next();
                    nextEntry.GetAttributeSet();

                    var cnx = nextEntry.GetAttribute("orclNetDescString").StringValue;

                    cache.Add(key, Tuple.Create <DateTime, string>(DateTime.Now, cnx));
                    return(cnx);
                }
            }
            catch (LdapException ldapEx)
            {
                ldapEx.ToString();
            }
            catch (Exception ex)
            {
                ex.ToString();
            }

            return(string.Empty);
        }
        // https://docs.bmc.com/docs/fpsc121/ldap-attributes-and-associated-fields-495323340.html
        private IReadOnlyDictionary <long, UserInfo> GetSearchResult(
            ILdapSearchResults searchResults,
            IReadOnlyCollection <DiscourseUser> users)
        {
            var result = new Dictionary <long, UserInfo>();

            try
            {
                while (searchResults.HasMore())
                {
                    var nextEntry     = searchResults.Next();
                    var userName      = nextEntry.GetAttribute("mail")?.StringValue?.Split('@')[0];
                    var discourseUser = users.FirstOrDefault(x => x.username == userName);
                    if (discourseUser != null)
                    {
                        result.Add(
                            discourseUser.id,
                            new UserInfo
                        {
                            Id       = discourseUser.id,
                            UserName = discourseUser.username,
                            Image    = nextEntry.GetAttribute("thumbnailPhoto")?.ByteValue,
                        });
                    }
                }
            }
            catch (LdapException ex)
            {
                if (ex.ResultCode != 10)
                {
                    throw;
                }
            }

            return(result);
        }
コード例 #7
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();
            }
        }
コード例 #8
0
 private static LdapEntry FindOne(this ILdapSearchResults results)
 {
     return(results.HasMore() ? results.Next() : null);
 }
コード例 #9
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;
                }
            }
        }
コード例 #10
0
        /// <summary>
        /// Executes the paged search.
        /// </summary>
        /// <returns>The paged search.</returns>
        /// <param name="searchBase">Search base.</param>
        /// <param name="filter">Filter.</param>
        /// <param name="cookie">Cookie to restore last search.</param>
        public LdapPagedResponse ExecutePagedSearch(string searchBase, string filter, string cookie = "")
        {
            var results = new List <LdapEntry>();

            var lcm  = LdapConnectionManager.Instance;
            var conn = lcm.GetConnection();

            var sb = searchBase + config.searchBase;


            // We will be sending two controls to the server
            LdapControl[] requestControls = new LdapControl[2];


            /* Create the sort key to be used by the sort control
             * Results should be sorted based on the cn attribute.
             * See the "NDS and Ldap Integration Guide" for information on
             * Novell eDirectory support of this functionaliry.
             */
            LdapSortKey[] keys = new LdapSortKey[1];
            keys[0] = new LdapSortKey("cn");

            // Create the sort control
            requestControls[0] = new LdapSortControl(keys, true);

            /* Create the VLV Control.
             * These two fields in the VLV Control identify the before and
             * after count of entries to be returned
             */
            //int beforeCount = 0;
            //int afterCount = 0;
            //int afterCount = config.maxResults -1;

            //System.String cookie = "";

            if (cookie != "")
            {
                byte[] data = System.Convert.FromBase64String(cookie);
                cookie = System.Text.Encoding.UTF8.GetString(data);
                //cookie = System.Text.ASCIIEncoding.ASCII.GetString(data);
            }


            requestControls[1] = new LdapPagedResultsControl(config.maxResults, cookie);

            // Set the controls to be sent as part of search request
            LdapSearchConstraints cons = conn.SearchConstraints;

            cons.SetControls(requestControls);
            conn.Constraints = cons;


            // Send the search request - Synchronous Search is being used here
            logger.Debug("Calling Asynchronous Search...");

            string[] attrs = null;

            ILdapSearchResults res = (LdapSearchResults)conn.Search(sb, LdapConnection.ScopeSub, filter, attrs, false, (LdapSearchConstraints)null);

            // Loop through the results and print them out
            while (res.HasMore())
            {
                /* Get next returned entry.  Note that we should expect a Ldap-
                 * Exception object as well just in case something goes wrong
                 */
                LdapEntry nextEntry = null;
                try
                {
                    nextEntry = res.Next();
                    results.Add(nextEntry);
                }
                catch (Exception e)
                {
                    if (e is LdapReferralException)
                    {
                        continue;
                    }
                    else
                    {
                        logger.Error("Search stopped with exception " + e.ToString());
                        break;
                    }
                }

                /* Print out the returned Entries distinguished name.  */
                logger.Debug(nextEntry.Dn);
            }

            var response = new LdapPagedResponse {
                Entries = results
            };

            // Server should send back a control irrespective of the
            // status of the search request
            LdapControl[] controls = ((LdapSearchResults)res).ResponseControls;
            if (controls == null)
            {
                logger.Debug("No controls returned");
            }
            else
            {
                // We are likely to have multiple controls returned
                for (int i = 0; i < controls.Length; i++)
                {
                    /* Is this the Sort Response Control. */
                    if (controls[i] is LdapPagedResultsResponse)
                    {
                        logger.Debug("Received Ldap Paged Control from Server");

                        LdapPagedResultsResponse cresp = new LdapPagedResultsResponse(controls[i].Id, controls[i].Critical, controls[i].GetValue());

                        cookie = cresp.Cookie;



                        byte[] hexCookie = System.Text.Encoding.UTF8.GetBytes(cookie);
                        response.Cookie = Convert.ToBase64String(hexCookie);

                        /*
                         * // Cookie is an opaque octet string. The chacters it contains might not be printable.
                         * byte[] hexCookie = System.Text.Encoding.ASCII.GetBytes(cookie);
                         * StringBuilder hex = new StringBuilder(hexCookie.Length);
                         * foreach (byte b in hexCookie)
                         *  hex.AppendFormat("{0:x}", b);
                         *
                         * System.Console.Out.WriteLine("Cookie: {0}", hex.ToString());
                         * System.Console.Out.WriteLine("Size: {0}", cresp.Size);
                         */
                    }
                }
            }


            return(response);
        }
コード例 #11
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);
        }
コード例 #12
0
        public AuthResult Login(string userName, string password)
        {
            using LdapConnection _connection = new LdapConnection { SecureSocketLayer = _config.SecureSocketLayer };
            try
            {
                _connection.Connect(_config.ServerHost, _config.ServerPort);
                _connection.Bind(_config.BindDN, _config.BindPassword);

                string             userFilter = string.Format(_config.UserFilter, userName);
                ILdapSearchResults result     = _connection.Search(
                    _config.BaseDN,
                    LdapConnection.ScopeSub,
                    userFilter,
                    new[] { DisplayName, Email, UserName },
                    false
                    );

                /*
                 * WARNING: Do not check result.Count == 0;
                 * "Count doesn't return "correctly" because is not blocking and doesn't wait to get the results and is
                 * returning whatever is available at that moment. It is true that this behavior
                 * is not the most expected one :) - and it may have an easy fix.
                 * It will return correctly after calling hasMore - which is blocking (e.g. wait for the result).
                 * Probably will be useful to make the "async" methods match the .net style.
                 * And even make the sync methods to return IEnumerable as will make the usage easier. Happy to take pull requests :)"
                 * https://github.com/dsbenghe/Novell.Directory.Ldap.NETStandard/issues/4
                 */
                if (!result.HasMore())
                {
                    return(new AuthResult
                    {
                        Errors = new List <string> {
                            "Invalid user"
                        }
                    });
                }

                LdapEntry user = result.Next();
                _connection.Bind(user.Dn, password);

                if (_connection.Bound)
                {
                    return(new AuthResult
                    {
                        AppUser = new AppUser
                        {
                            Email = user.GetAttribute(Email).StringValue,
                            DisplayName = user.GetAttribute(DisplayName).StringValue,
                            UserName = user.GetAttribute(UserName).StringValue,
                        }
                    });
                }
                else
                {
                    return(new AuthResult
                    {
                        Errors = new List <string> {
                            "Invalid user"
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                return(new AuthResult
                {
                    Errors = new List <string> {
                        ex.Message
                    }
                });
            }
        }