We have a AD Forest, there are two different domains. Lets say that we have domain A and Domain B. We have a group "Admins" in the domain A. In this group were added several groups from the domain B. How can I check, whether a user belongs to the "Admin" group or to the group that is in "Admin" group?
Scenario I considered:
- Find Admins group in domain A.
- Read all groups and users that belong to the "Admin" group
- Find all groups for the current UserPrincipal It could be that principal belongs to groups in Domain A and domain B.
- Compare the two lists with respective SIDs
Is it safe to compare the SID of a group object from domain A with the SID of the very same group that was added(linked) to the domain B? are the SIDs always unique in terms of one Forest?
Update: One can use the solution proposed by Ashigore. Or the solution I wrote:
public IEnumerable<SecurityIdentifier> ReadAllMemebersForRecursive(string groupName)
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domainname", "user to access", "password");
var groupPrincipal = GroupPrincipal.FindByIdentity(ctx, groupName);
if (groupPrincipal == null)
return Enumerable.Empty<SecurityIdentifier>();
return groupPrincipal.GetMembers(true).OfType<UserPrincipal>().Select(gp => gp.Sid);
}
IEnumerable<SecurityIdentifier> users = service.ReadAllMemebersForRecursive(groupName);
var identity = WindowsIdentity.GetCurrent();
var admin = users.Contains(identity.User);