C# 从当前登录用户的 Active Directory 中获取专有名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10428495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:49:16  来源:igfitidea点击:

Get distinguished name from Active Directory of currently logged in user

c#.netactive-directorydistinguishedname

提问by Tunc Jamgocyan

How can I get the distinguished name from Active Directory of the currently logged in user in C#?

如何从 C# 中当前登录用户的 Active Directory 中获取可分辨名称?

采纳答案by empi

Check following snippet. You have pass to Identity.Namefrom IPrincipal. I assume that the user is already authenticated in Active Directory (ie. using standard IIS authorization methods).

检查以下代码段。你已经Identity.NameIPrincipal传到了。我假设用户已经在 Active Directory 中进行了身份验证(即使用标准的 IIS 授权方法)。

private string GetUserName(string identity)
{
    if (identity.Contains("\"))
    {
        string[] identityList = identity.Split('\');
        return identityList[1];
    }
    else
    {
        return identity;
    }
}

public string GetUserDn(string identity)
{            
    var userName = GetUserName(identity);   
    using (var rootEntry = new DirectoryEntry("LDAP://" + adConfiguration.ServerAddress, null, null, AuthenticationTypes.Secure))
    {       
        using (var directorySearcher = new DirectorySearcher(rootEntry, String.Format("(sAMAccountName={0})", userName)))
        {
            var searchResult = directorySearcher.FindOne();                    
            if (searchResult != null)
            {
                using (var userEntry = searchResult.GetDirectoryEntry())
                {
                    return (string)userEntry.Properties["distinguishedName"].Value;                 
                }
            }
        }                
    }   
    return null;
}        

回答by John Ruiz

Why wouldn't you just use: System.DirectoryServices.AccountManagement.UserPrincipal.Current.DistinguishedName

你为什么不直接使用: System.DirectoryServices.AccountManagement.UserPrincipal.Current.DistinguishedName