Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用下级用户名检索用户主体对象_C#_.net_Active Directory_Iprincipal - Fatal编程技术网

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

C# 使用下级用户名检索用户主体对象,c#,.net,active-directory,iprincipal,C#,.net,Active Directory,Iprincipal,我从AD检索用户主体对象时遇到问题,如下所示: public static UserPrincipal GetUserPrincipalByUserName(string userName, IdentityType identityType, string adUsername, string adPassword, string adDomain) { UserPrincipal result; try { using (PrincipalContex

我从AD检索用户主体对象时遇到问题,如下所示:

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;
}
一切都很正常,对吧?但是,在我的web应用程序中,我从
User.Identity.Name
中提取用户名,这将以低级格式(域\用户名)提供用户名,而不是UPN(username@domain.com). 我的单元测试(1和2)通过UPN或SAM IdentityType,但不通过提供的底层名称(3),也不通过使用IdentityType的非限定用户名(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并使用它吗?

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

  • 底层域名不会直接映射到UPN(缺少域后缀的信息),因此基本上不能在两者之间进行文本转换
  • User.Identity.Name
    仍然是个谜-请参见我的其他问题: