ProfK
ProfK

Reputation: 51063

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();

Upvotes: 5

Views: 2642

Answers (1)

marc_s
marc_s

Reputation: 754230

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...

Upvotes: 6

Related Questions