How to Verify if the user belongs to an Active Directory user Group in C#.NET
I am writing code to verify whether user belongs to a particular AD group or not.
When i checked this is how the group details are:
"CN=Building - 28 (ALL),OU=Exchange Auto Groups,OU=AM,OU=schwab,DC=am,DC=corp,DC=schwab,DC=com"
This is the group that I want to verify if a user (Ex: user1) belongs to this group or not.
I am try开发者_如何转开发ing to play with the method that returns the list of Groups that the User belongs to. Here I have to filter based on the Group.
Code to bring the active directory user groups that the user belongs to:
private List<string> GetUserGroupMembership(string userName)
{
var directoryEntry = new DirectoryEntry();
DirectorySearcher search = new DirectorySearcher();
**//filter based on the username**
search.Filter = String.Format("(cn={0})", userName);
**//How to filter based on the Group "CN=Building - 28 (ALL),OU=Exchange Auto Groups,OU=AM,OU=schwab,DC=am,DC=corp,DC=schwab,DC=com"**
search.PropertiesToLoad.Add("memberOf");
List<string> groupsList = new List<string>();
SearchResult result = search.FindOne();
if (result != null)
{
int groupCount = result.Properties["memberOf"].Count;
for (int counter = 0; counter < groupCount; counter++)
{
groupsList.Add((string)result.Properties["memberOf"][counter]);
}
}
return groupsList.ToList();
}
I appreciate your response.
Thanks
If you are using .NET 3.5 or later then have a look at System.DirectoryServices.AccountManagement. These classes are far easy to work with. For example,
PrincipalContext pc = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(pc, "johndoe");
var groups = user.GetAuthorizationGroups() // or user.GetUserGroups()
Have a look at these article that gives a bit of overview for the same:
http://anyrest.wordpress.com/2010/06/28/active-directory-c/
http://msdn.microsoft.com/en-us/magazine/cc135979.aspx#S5
精彩评论