我在从AD检索User Principal对象时遇到问题,如下所示:
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;
}
一切都很正常吗?但是,在我的网络应用程序中,我从User.Identity.Name
中提取了用户名,它以低级格式(域\用户名)提供了用户名,而不是我的UPN(username@domain.com) 。我的单元测试(1和2)使用IdentityType.Name传递UPN或SAM IdentityTypes,但不传递提供的下级名称(3),也不传递非限定用户名(4):
[TestClass]
public class ActiveDirectoryTests
{
public const string Username = "jdoe";
public const string DownLevelUsername = "DOMAIN\\jdoe";
public const string Upn = "jdoe@domain.com";
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));
}
}
我是否可以执行此任务而无需对User.Identity.Name
的下级名称进行任意字符串解析?可以/我应该从用户对象中挖出SID并使用它吗?
答案 0 :(得分:1)
我只是通过使用SID解决了我自己的问题,但是对于信息:
User.Identity.Name
仍然是一个谜 - 请在此处查看我的另一个问题:What does System.DirectoryServices.AccountManagement.IdentityType.Name specify?