User to be validated against nested security groups in Windows.
- by user412272
Hi,
This is my first post here and after much looking around I have come here with my question. Will really appreciate a fast response.
I am faced with a problem to validate user credentials of the currently logged on user against a group in Windows. The user membership to a group can be through other groups also ie nested membership. Eg. User U is a part of group G1. Group G1 is a part of another group G2. The requirement is that when the user is validated against group G2, the validations should succeed.
The user can be a local or AD user but the group will always be a local group ( or domain local group if created directly on a DC).
I have tried using WindowsPrincipal.IsInRole() method, but it seems to be checking only for direct membership to a group. I also tried UserPrincipal.GetAuthorizationGroups() for the current user, but it also doesnt seem to be doing recursive search.
I am posting a code snippet of the working code below, but this code is taking much more than acceptable time.
bool CheckUserPermissions(string groupName)
{
WindowsIdentity currentUserIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
bool found = false;
PrincipalContext context= new PrincipalContext(ContextType.Machine);
GroupPrincipal group = GroupPrincipal.FindByIdentity(context, IdentityType.Name, groupName);
if (group!= null)
{
foreach (Principal p in group.GetMembers(true))
{
if (p.Sid == currentUserIdentity.User)
{
found = true;
break;
}
}
group.Dispose();
}
return found;
}