Home > database >  How can I retrieve the phone number from Active Directory using User Principal Context
How can I retrieve the phone number from Active Directory using User Principal Context

Time:03-31

This code works perfectly to get the phone number from Active Directory using the username and password

    public string GetPhone(string domain, string username, string pwd)
    {
        _path = "LDAP://"   domain;
        string domainAndUsername = domain   @"\"   username;
        DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);
        string telephoneNumber = string.Empty;

        try
        {
            object obj = entry.NativeObject;
            DirectorySearcher search = new DirectorySearcher(entry);

            SearchResult result = search.FindOne();

            var myEntry = result.GetDirectoryEntry();
            telephoneNumber = myEntry.Properties["telephoneNumber"].Value.ToString();
        }
        catch (Exception ex)
        {

            throw new Exception("Error obtaining phone number. "   ex.Message);
        }
        return telephoneNumber;
    }

However, I have access to the user password only on the login page. I do have the User context being generated though that is accessible from anywhere within the application (Context.User which is of System.Security.Principal.IPrincipal type)

Thus, how can I get the phone from Active Directory using an already available Context.User object?

Thank you very much in advance

CodePudding user response:

The User object you get will have the SID of the user. With that, you can use the SID binding LDAP path in DirectoryEntry: LDAP://<SID=XXXXX>

var user = new DirectoryEntry(
    $"LDAP://<SID={((WindowsIdentity) HttpContext.User.Identity).User.Value}>");

user.RefreshCache(new [] { "telephoneNumber" });
var telephoneNumber = user.Properties["telephoneNumber"]?.Value as string;

The use of RefreshCache is to load only the telephoneNumber attribute. Otherwise, when you first use .Properties, it will retrieve every attribute, which is a waste of time and bandwidth.

CodePudding user response:

Looks like I overcomplicated everything and solution is quite simple

    private void SetPhone()
    {
        DirectoryEntry entryDomain = new DirectoryEntry("LDAP://"   domain);
        DirectorySearcher ds = new DirectorySearcher(entryDomain);

        string lastName = Context.User.Identity.Name.Split(' ')[Context.User.Identity.Name.Split(' ').Length - 1];

        ds.Filter = "(sn="   lastName   ")";
        SearchResult sr = ds.FindOne();

        string telephoneNumber = sr.Properties["telephoneNumber"][0].ToString();
        telephoneNumber = telephoneNumber.Insert(0, "(").Insert(4, ")").Insert(5, " ").Insert(9, "-");
        Session["UserPhone"] = String.Format("{0:(###) ###-####}", telephoneNumber); ;
    }
  • Related