The IT department approval process for creating new AD groups is very cumbersome, so I've been tasked with looking at ways to use local groups to control access.
On Windows Server 2008 R2 I have created a local group, and have added several other AD groups along with some AD user accounts as members.
I need to write some C# code to determine if a particular AD user belongs to a particular local group, where the local group contains a mixture of AD groups and AD users. The AD groups may in some cases contain nested AD groups.
Update
The code below works when a domain user account is directly a member of a local group, but it does not work when a local group contains a domain group which the domain user is a member of.
public static void Test()
{
// returns true, domain user account user623 is in domain group ...
bool b1 = UserIsInDomainGroup("user623", "apc.app.cartopac.surfaceland");
// returns true - user623 is directly in local.groupa
bool b2 = UserIsInlocalGroup("user623", "local.groupa");
// returns false, even though apc.app.cartopac.surfaceland is in local.groupb
bool b3 = UserIsInlocalGroup("user623", "local.groupb");
}
public static bool UserIsInDomainGroup(string userName, string grpName)
{
var domainContext = new PrincipalContext(ContextType.Domain, "contoso");
var user = UserPrincipal.FindByIdentity(domainContext, userName);
return user.IsMemberOf(domainContext, IdentityType.Name, grpName);
}
public static bool UserIsInlocalGroup(string userName, string localgrpName)
{
var machineContext = new PrincipalContext(ContextType.Machine);
var grpPrincipal = GroupPrincipal.FindByIdentity(machineContext, IdentityType.Name, localgrpName);
var domainContext = new PrincipalContext(ContextType.Domain, "contoso");
var user = UserPrincipal.FindByIdentity(domainContext, userName);
return user.IsMemberOf(grpPrincipal);
}
user.IsMemberOf(grpPrincipal)
?? Does that work for you? – marc_s