Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    }
like image 455
user2224493 Avatar asked Dec 16 '15 18:12

user2224493


People also ask

How do I list all ad groups in a user?

Use Get-ADGroupMember cmdlet to List Members of an Active Directory Group. The PowerShell Get-ADGroupMember cmdlet is used to list the members of an Active Directory group. You can just type the cmdlet in a PowerShell window and you'll be prompted to enter the name of the group you want to use.

What is Groupprincipal?

This principle states that every group so formed and every member who is a part of such a group is responsible for the continuous functioning of the same group. Groups adjourn only upon the completion of the task or the achievement of the goal.

What is ADPrincipalGroupMembership?

Description. The Get-ADPrincipalGroupMembership cmdlet gets the Active Directory groups that have a specified user, computer, group, or service account as a member. This cmdlet requires a global catalog to perform the group search.


2 Answers

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;
}
like image 116
Dave Greilach Avatar answered Oct 22 '22 08:10

Dave Greilach


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);
            }
like image 39
michellhornung Avatar answered Oct 22 '22 09:10

michellhornung