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
2
Answers
Looks like I overcomplicated everything and solution is quite simple
The
User
object you get will have the SID of the user. With that, you can use the SID binding LDAP path inDirectoryEntry
:LDAP://<SID=XXXXX>
The use of
RefreshCache
is to load only thetelephoneNumber
attribute. Otherwise, when you first use.Properties
, it will retrieve every attribute, which is a waste of time and bandwidth.