Suppose user johnsmith is a member of an active directory group MyManagers. Suppose group MyManagers is a member of the group MyEmployees. Suppose group MyEmployees is a member of the group MyUsers.
When johnsmith logs in to my application, how can I know that he is a member of the group MyUsers?
Appreciate examples in C#.
Thanks, kruvi
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement
(S.DS.AM) namespace. Read all about it here:
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user
UserPrincipal user = UserPrincipal.Current; // this would be John Smith
if(user != null)
{
// get the user's groups he's a member of
PrincipalSearchResult<Principal> results = user.GetAuthorizationGroups();
// now you just need to iterate over the groups and see if you find the
// one group you're interested in
}
The GetAuthorizationGroups
call in S.DS.AM does indeed do recursive querying, e.g. it will also pick up any groups your user is a member of because of groups being members of other groups.
The new S.DS.AM makes it really easy to play around with users and groups in AD!