Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get Novell.Directory.Ldap.NETStandard library to query

I need to let the user query an Active Directory for names in .Net Core. So I am building an Active Directory Search Web API Service.

I am able to connect with the bind statement. But I am not able to get any results back with my query although there is no error.

Another programmer sent me some code he uses in other applications. But it uses the DirectoryEntry object which is not available in .Net Core.

So I am trying to use the Novell.Directory.Ldap.NetStandard library.

Here is the code the other developer sent me:

public static List<UserProfileModel> GetADUsers(string alias)
    {
        List<UserProfileModel> users = new List<UserProfileModel>();

        if (alias == null || alias.Trim().Equals(""))
        {
            return users;
        }

        try
        {
            // Ad path LDAP://ourOrg.gov/CN=Users,DC=ourOrg,DC=gov
            DirectoryEntry de2 = new DirectoryEntry(ConfigurationManager.AppSettings["AD_Path"], ConfigurationManager.AppSettings["AD_User"], ConfigurationManager.AppSettings["AD_Password"]);
            de2.Path = ConfigurationManager.AppSettings["AD_Path"];

            de2.AuthenticationType = AuthenticationTypes.Secure;

            DirectorySearcher deSearch = new DirectorySearcher();

            deSearch.SearchRoot = de2;
            deSearch.Filter = "(samaccountname=*" + alias + "*)";

            LOGGER.Debug(String.Format("Active Directory Search Filter {0}", deSearch.Filter));

            SearchResultCollection results = deSearch.FindAll();
            String raw = "";

            LOGGER.Debug(String.Format("Active Directory Search Result Counts {0}", results.Count));

            if (results.Count > 0)
            {
                foreach (SearchResult item in results)
                {
                    UserProfileModel userProfileModel = new UserProfileModel();

                    userProfileModel.Name = GetADProperty("name", item);
                    userProfileModel.email = GetADProperty("mail", item);
                    userProfileModel.identity = GetADProperty("userPrincipalName", item);
                    userProfileModel.first_name = GetADProperty("givenName", item);
                    userProfileModel.last_name = GetADProperty("sn", item);
                    users.Add(userProfileModel);
                    raw = String.Format("{0}/n{1}", raw, userProfileModel.ToString());
                }
                LOGGER.Debug(String.Format("Active Directory Search Resuts ToString: {0}", raw));
            }
        }
        catch (Exception e)
        {
            LOGGER.Error("Unable to Query Active Directory", e);
        }

        return users;
    }

I need to translate this into Novell's LDAP library.

Here is my attempt:

    [HttpGet]
    public async Task<List<UserProfileModel>> GetByName(string alias)
    {

        int ldapPort = LdapConnection.DEFAULT_PORT;
        string ldapHost = "ourOrg.gov";
        string loginDn = @"ourOrg\myName";
        string password = "myPass";

        List<UserProfileModel> users = new List<UserProfileModel>();

        if (alias == null || alias.Trim().Equals(""))
        {
            return users;
        }

        try
        {
            using (var con = new LdapConnection())
            {
                con.Connect(ldapHost, ldapPort);
                con.Bind(loginDn, password);

                LdapSearchResults results = con.Search(
                    "cn=users,dc=ourOrg,dc=gov",
                    LdapConnection.SCOPE_ONE,
                    "samaccountname=*",
                    null,
                    false);

                // NO RESULTS:(
            }

            return users;
        }
        catch(Exception ex)
        {
            throw ex;
        }

    }

I don't get an error. But there are 0 results.

I originally had this part:

"samaccountname=*",

like:

"samaccountname={alias}",

but I'm just trying to get back results at this point.

like image 591
Sam Avatar asked Jun 02 '17 16:06

Sam


1 Answers

I got this working:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Hrsa.Core.Web.App.Models.ViewModels;
using Novell.Directory.Ldap;

// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace Hrsa.Core.Web.App.Controllers.Api
{
    [Route("api/[controller]")]
    public class ActiveDirectoryController : Controller
    {
        private readonly AppSettings _appSettings;

        public ActiveDirectoryController(IOptions<AppSettings> appSettings)
        {
            _appSettings = appSettings.Value;
        }

        [HttpGet]
        public async Task<List<UserProfileModel>> GetByName(string alias)
        {
            int ldapPort = LdapConnection.DEFAULT_PORT;
            string ldapHost = _appSettings.HrsaLdapHost;    // ourOrgName.gov
            string loginDn = _appSettings.AdUser;
            string password = _appSettings.AdPassword;

            string searchBase = _appSettings.HrsaAdSearchBase;
            string searchFilter = $"(samaccountname=*{alias}*)";
            string[] attributes = new string[] { "cn", "userPrincipalName", "st", "givenname", "samaccountname",
                "description", "telephonenumber", "department", "displayname", "name", "mail", "givenName", "sn" };

            List<UserProfileModel> users = new List<UserProfileModel>();

            if (alias == null || alias.Trim().Equals(""))
            {
                return users;
            }

            try
            {
                using (var con = new LdapConnection())
                {
                    con.Connect(ldapHost, ldapPort);
                    con.Bind(loginDn, password);

                    LdapSearchQueue queue = con.Search(
                        searchBase,
                        LdapConnection.SCOPE_SUB,
                        searchFilter,
                        attributes,
                        false,
                        (LdapSearchQueue)null,
                        (LdapSearchConstraints)null);

                    LdapMessage message;

                    while ((message = queue.getResponse()) != null)
                    {
                        if (message is LdapSearchResult)
                        {
                            LdapEntry entry = ((LdapSearchResult)message).Entry;

                            LdapAttributeSet attributeSet = entry.getAttributeSet();

                            users.Add(new UserProfileModel
                            {

                                Cn = attributeSet.getAttribute("cn")?.StringValue,
                                UserPrincipalName = attributeSet.getAttribute("userPrincipalName")?.StringValue,
                                St = attributeSet.getAttribute("st")?.StringValue,
                                Givenname = attributeSet.getAttribute("givenname")?.StringValue,
                                Samaccountname = attributeSet.getAttribute("samaccountname")?.StringValue,
                                Description = attributeSet.getAttribute("description")?.StringValue,
                                Telephonenumber = attributeSet.getAttribute("telephonenumber")?.StringValue,
                                Department = attributeSet.getAttribute("department")?.StringValue,
                                Displayname = attributeSet.getAttribute("displayname")?.StringValue,
                                Name = attributeSet.getAttribute("name")?.StringValue,
                                Mail = attributeSet.getAttribute("mail")?.StringValue,
                                GivenName = attributeSet.getAttribute("givenName")?.StringValue,
                                Sn = attributeSet.getAttribute("sn")?.StringValue
                            });
                        }
                    }
                }

                return users;
            }
            catch(Exception ex)
            {
                throw ex;
            }

        }
    }
}
like image 85
Sam Avatar answered Sep 21 '22 11:09

Sam