Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a user's group memberships from Active Directory

How can I about getting a user's group memberships from AD, preferably using the same pattern as I use to get the user's Department property, as below? I have found several examples, but the intersecting set of all example techniques is quite small, and lacks the tightness and simplicity of this Department query:

        var adServer = ConfigurationManager.AppSettings["adServer"] ?? "localhost";
        var remoteRoot = new DirectoryEntry(GetRootPath(adServer));
        var searcher = new DirectorySearcher(remoteRoot, string.Format("(SAMAccountName={0})", shortUserName));

        searcher.PropertiesToLoad.Add("Department");
        SearchResult result = null;
        result = searcher.FindOne();
like image 438
ProfK Avatar asked Dec 29 '09 10:12

ProfK


People also ask

How do I check my Active Directory group membership?

Go to “Active Directory Users and Computers”. Click on “Users” or the folder that contains the user account. Right click on the user account and click “Properties.” Click “Member of” tab.

How do I Export my ad user membership?

Run Netwrix Auditor → Navigate to "Reports" → Expand the "Active Directory" section → Go to "Active Directory - State-in-Time" → Select "User Accounts - Group Membership"→ Click 'View". To save the report, click the "Export" button → Choose a format from the dropdown menu → Click "Save".

How do you find the list of all groups a user is member of?

To get (sorted) plain list of groups only, you can run (New-Object System. DirectoryServices. DirectorySearcher("(&(objectCategory=User)(samAccountName=$($env:username)))")). FindOne().


1 Answers

Are you on .NET 3.5 ? If so, it's very easy:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");

string userName = "yourUser";

UserPrincipal user = UserPrincipal.FindByIdentity(ctx, userName);

PrincipalSearchResult<Principal> results = user.GetAuthorizationGroups();

Find your user, and then call the .GetAuthorizationGroups() on your user principal - that returns all groups the user belongs to, including his primary group, and any nested group memberships.

Check out this MSDN article for more new goodness in .NET 3.5 when it comes to dealing with AD.

In .NET 2.0, things are a lot messier...

like image 53
marc_s Avatar answered Sep 28 '22 10:09

marc_s