Get distinguished name from Active Directory of currently logged in user

社会主义新天地 提交于 2019-12-24 15:05:40

问题


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


回答1:


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

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;
}        



回答2:


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



来源:https://stackoverflow.com/questions/10428495/get-distinguished-name-from-active-directory-of-currently-logged-in-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!