user2224493
user2224493

Reputation: 269

Return a list of all Active Directory groups a user belongs to in string[ ]

I need to return all Active Directory groups a user belongs to but in string[ ], so I can use the result in Generic Principal.

I am not sure if to cast results? Please help!

string[] roles = new string[] {  
helper.GetActiveDirectoryGroups(User.Identity.Name) };

GenericPrincipal principal = new GenericPrincipal(identity,roles);

 public string[] GetActiveDirectoryGroups(string userName)
    {
          //code here

    }

Upvotes: 9

Views: 15432

Answers (2)

michellhornung
michellhornung

Reputation: 21

In case you want to return a bool value if user belongs to a group, here it go:

 string[] output = null;
            using (var ctx = new PrincipalContext(ContextType.Domain, domain))
            using (var user = UserPrincipal.FindByIdentity(ctx, username))
            {
                if (user != null)
                {
                    output = user.GetGroups()
                        .Select(x => x.SamAccountName)
                        .ToArray();
                }

                bool isMember = output.Any(groupName.Contains);
            }

Upvotes: 2

Dave Greilach
Dave Greilach

Reputation: 895

This should do the trick.

using System.DirectoryServices.AccountManagement;

public static string[] GetGroups(string username)
{
    string[] output = null;

    using (var ctx = new PrincipalContext(ContextType.Domain))
    using (var user = UserPrincipal.FindByIdentity(ctx, username))
    {
        if (user != null)
        {
            output = user.GetGroups() //this returns a collection of principal objects
                .Select(x => x.SamAccountName) // select the name.  you may change this to choose the display name or whatever you want
                .ToArray(); // convert to string array
        }
    }

    return output;
}

Upvotes: 15

Related Questions