使用下级用户名检索用户主体对象

时间:2013-08-27 14:47:43

标签: c# .net active-directory iprincipal

我在从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并使用它吗?

1 个答案:

答案 0 :(得分:1)

我只是通过使用SID解决了我自己的问题,但是对于信息: