How to get a username in Active Directory from a display name in C#?

前端 未结 2 602
遇见更好的自我
遇见更好的自我 2021-02-01 07:10

I want to be able to obtain the userid of a user in Active Directory using the display name of that user. The display name is obtained from a database, and has been stored durin

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-01 08:06

    UserPrincipal has a method GetUnderlyingObject() which will return the DirectoryEntry.

    Get DirectoryEntry from Principal:

    private DirectoryEntry GetDirectoryEntryFromUserPrincipal(Principal user)
    {
        return (DirectoryEntry)user.GetUnderlyingObject();
    }
    

    Get DirectoryEntry from domain and account name:

    private DirectoryEntry GetDirectoryEntryFromDomainAndUsername(string domainName, string userName)
    {
        // Get the sid from the NT account name
        var sid = (SecurityIdentifier) new NTAccount(domainName, accountName)
                      .Translate(typeof(SecurityIdentifier));
    
        // Get the directory entry for the LDAP service account
        var serviceEntry = new DirectoryEntry("LDAP://{address}", "serviceUsername", "servicePassword");
    
        var mySearcher = new DirectorySearcher(serviceEntry)
            {
                Filter = string.Format("(&(ObjectSid={0}))", sid.Value)
            };
    
        return mySearcher.FindOne().GetDirectoryEntry();
    }
    

    Once you have the DirectoryEntry use the Guid property to get the entry's Object-Guid

    private Guid GetObjectGuidFromDirectoryEntry(DirectoryEntry entry)
    {
        // return the Guid this is the Object-Guid (ignore NativeGuid)
        return entry.Guid;
    }
    

    For tracking a user account in the application against a directory account: always use the Object-Guid as "This value is set when the object is created and cannot be changed."
    NT and SAM account names can change if the user changes domains or, more commonly, changes their name (marriage, legal name-change, etc.) and should not be used to track a user.

    To get the NT account name (domain\username):

    private string GetNTAccountNameFromDirectoryEntry(DirectoryEntry entry)
    {
        PropertyValueCollection propertyValueCollection = entry.Properties["objectsid"];
    
        SecurityIdentifier sid = new SecurityIdentifier((byte[]) propertyValueCollection[0], 0);
    
        NTAccount ntAccount = (NTAccount)sid.Translate(typeof (NTAccount));
    
        return account.ToString();
    }
    

    To get the SAM-Account-Name (username@domain):

    private string GetSAMAccountFromDirectoryEntry(DirectoryEntry entry)
    {
        return entry.Properties["Name"].Value;
    }
    

    And here's the exhaustive list of all the Active Directory attributes. Use the "Ldap-Display-Name" when getting the value from Properties
    e.g. Properties["Ldap-Display-Name"]

    Display-Name (FirstName MI LastName) might come in handy.

提交回复
热议问题