Reputation: 269
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
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
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