UserPrincipal
has a method GetUnderlyingObject()
which will return the DirectoryEntry
.
Get DirectoryEntry from Principal:
private DirectoryEntry GetDirectoryEntryFromUserPrincipal(Principal user)
{
return (DirectoryEntry)user.GetUnderlyingObject();
}
Get DirectoryEntry from domain and account name:
private DirectoryEntry GetDirectoryEntryFromDomainAndUsername(string domainName, string userName)
{
// Get the sid from the NT account name
var sid = (SecurityIdentifier) new NTAccount(domainName, accountName)
.Translate(typeof(SecurityIdentifier));
// Get the directory entry for the LDAP service account
var serviceEntry = new DirectoryEntry("LDAP://{address}", "serviceUsername", "servicePassword");
var mySearcher = new DirectorySearcher(serviceEntry)
{
Filter = string.Format("(&(ObjectSid={0}))", sid.Value)
};
return mySearcher.FindOne().GetDirectoryEntry();
}
Once you have the DirectoryEntry
use the Guid
property to get the entry's Object-Guid
private Guid GetObjectGuidFromDirectoryEntry(DirectoryEntry entry)
{
// return the Guid this is the Object-Guid (ignore NativeGuid)
return entry.Guid;
}
For tracking a user account in the application against a directory account: always use the Object-Guid as "This value is set when the object is created and cannot be changed."
NT and SAM account names can change if the user changes domains or, more commonly, changes their name (marriage, legal name-change, etc.) and should not be used to track a user.
To get the NT account name (domain\username):
private string GetNTAccountNameFromDirectoryEntry(DirectoryEntry entry)
{
PropertyValueCollection propertyValueCollection = entry.Properties["objectsid"];
SecurityIdentifier sid = new SecurityIdentifier((byte[]) propertyValueCollection[0], 0);
NTAccount ntAccount = (NTAccount)sid.Translate(typeof (NTAccount));
return account.ToString();
}
To get the SAM-Account-Name (username@domain):
private string GetSAMAccountFromDirectoryEntry(DirectoryEntry entry)
{
return entry.Properties["Name"].Value;
}
And here's the exhaustive list of all the Active Directory attributes. Use the "Ldap-Display-Name" when getting the value from Properties
e.g. Properties["Ldap-Display-Name"]
Display-Name (FirstName MI LastName) might come in handy.
SamAccountName
property.