How to determine the type (AD User vs. AD Group) of an account?

后端 未结 2 413
庸人自扰
庸人自扰 2020-12-21 10:29

I have a question about determining the type (User or Group) of a account name.
For example, I have two strings, say \"Adventure-works\\david\" and \"Adventure-works\\ad

相关标签:
2条回答
  • 2020-12-21 10:51

    Warning: In case of using DirectorySearcher the accepted answer might fail, since objectCategory it doesn't return consistent results.

    Consider using objectClass instead:

    SearchResult sr = ds.FindOne();
    bool isUser = sr.Properties["objectClass"]?.Contains("user") == true;
    // OR
    bool isGroup = sr.Properties["objectClass"]?.Contains("group") == true;
    
    0 讨论(0)
  • 2020-12-21 11:06

    What version of .NET are you on??

    If you're on .NET 3.5, see this excellent MSDN article on how the Active Directory interface has changed quite a bit.

    If you're on .NET 3.5, you could write:

    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
    Principal myObject = Principal.FindByIdentity(ctx, "your name value");
    

    Typically, you'd have to pass in just the user name - the part after the backslash - not the whole DOMAIN\USERNAME string.

    This "Principal" now either is a UserPrincipal or a GroupPrincipal (or it could some other type of principal, e.g. ComputerPrincipal):

    if(myObject is UserPrincipal)
    {
        // you have a user
    }
    else if(myObject is GroupPrincipal)
    {
        // you have a group
    }
    

    and you can go on from there.


    If you're on .NET 1.x/2.0/3.0, you'd have to use the slightly more involved procedure of creating a DirectorySearcher and searching for your object:

    // create root DirectoryEntry for your search
    DirectoryEntry deRoot = new DirectoryEntry("LDAP://dc=YourCompany,dc=com");
    
    // create searcher            
    DirectorySearcher ds = new DirectorySearcher(deRoot);
    
    ds.SearchScope = SearchScope.Subtree;
    
    // define LDAP filter - all you can specify is the "anr" (ambiguous name
    // resolution) attribute of the object you're looking for
    ds.Filter = string.Format("(anr={0})", "YourNameValue");
    
    // define properties you want in search result(s)
    ds.PropertiesToLoad.Add("objectCategory");
    ds.PropertiesToLoad.Add("displayName");
    
    // search
    SearchResult sr = ds.FindOne();
    
    // check if we get anything back, and if we can check the "objectCategory" 
    // property in the search result
    if (sr != null)
    {
        if(sr.Properties["objectCategory"] != null)
        {
           // objectType will be "Person" or "Group" (or something else entirely)
           string objectType = sr.Properties["objectCategory"][0].ToString();
        }
    }
    

    Marc

    0 讨论(0)
提交回复
热议问题