I'm having problems retrieving the User Principal object from AD as follows:
public static UserPrincipal GetUserPrincipalByUserName(string userName, IdentityType identityType, string adUsername, string adPassword, string adDomain)
{
UserPrincipal result;
try
{
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, adDomain, adUsername, adPassword))
{
result = UserPrincipal.FindByIdentity(pc, identityType, userName);
}
}
catch
{
result = null;
}
return result;
}
All pretty normal right? However, in my web application, I'm pulling out the username from User.Identity.Name
, which gives me the username in the down-level format (domain\username), not my UPN ([email protected]). My unit tests (1 and 2) pass on the UPN or SAM IdentityTypes, but not on the down-level name provided (3), nor the unqualified username (4), using IdentityType.Name:
[TestClass]
public class ActiveDirectoryTests
{
public const string Username = "jdoe";
public const string DownLevelUsername = "DOMAIN\\jdoe";
public const string Upn = "[email protected]";
public const string AdUsername = "username";
public const string AdPassword = "password";
public const string AdDomain = "domain";
[TestMethod]
public void SearchByUpn()
{
Assert.IsNotNull(ActiveDirectory.SafeGetUserPrincipalByUserName(Upn, IdentityType.UserPrincipalName, AdUsername, AdPassword, AdDomain));
}
[TestMethod]
public void SearchBySamUsername()
{
Assert.IsNotNull(ActiveDirectory.SafeGetUserPrincipalByUserName(Username, IdentityType.SamAccountName, AdUsername, AdPassword, AdDomain));
}
[TestMethod]
public void SearchByDownLevelUsername()
{
Assert.IsNotNull(ActiveDirectory.SafeGetUserPrincipalByUserName(DownLevelUsername, IdentityType.Name, AdUsername, AdPassword, AdDomain));
}
[TestMethod]
public void SearchByUnqualifiedUsername()
{
Assert.IsNotNull(ActiveDirectory.SafeGetUserPrincipalByUserName(Username, IdentityType.Name, AdUsername, AdPassword, AdDomain));
}
}
Can I do this task without just doing some arbitrary string parsing on the down-level name that I get from User.Identity.Name
? Can/should I just dig the SID out of the user object and use that instead?
I fixed my own problem just by using the SID, but for info:
User.Identity.Name
is still a mystery - see my other question here: What does System.DirectoryServices.AccountManagement.IdentityType.Name specify?