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
}
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.
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.
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.
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;
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With