How to get all the AD groups for a particular user?

后端 未结 10 1689
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 04:19

I checked this post already. But it doesn\'t answer my question. I want to get all the active directory groups in which a particular user is a member.

I\'ve written

10条回答
  •  孤街浪徒
    2020-11-28 05:14

    If you have a LDAP connection with a username and password to connect to Active Directory, here is the code I used to connect properly:

    using System.DirectoryServices.AccountManagement;
    
    // ...
    
    // Connection information
    var connectionString = "LDAP://domain.com/DC=domain,DC=com";
    var connectionUsername = "your_ad_username";
    var connectionPassword = "your_ad_password";
    
    // Get groups for this user
    var username = "myusername";
    
    // Split the LDAP Uri
    var uri = new Uri(connectionString);
    var host = uri.Host;
    var container = uri.Segments.Count() >=1 ? uri.Segments[1] : "";
    
    // Create context to connect to AD
    var princContext = new PrincipalContext(ContextType.Domain, host, container, connectionUsername, connectionPassword);
    
    // Get User
    UserPrincipal user = UserPrincipal.FindByIdentity(princContext, IdentityType.SamAccountName, username);
    
    // Browse user's groups
    foreach (GroupPrincipal group in user.GetGroups())
    {
        Console.Out.WriteLine(group.Name);
    }
    

提交回复
热议问题