mardi 4 août 2015

Validating user against AD group, throws an exception when group contains deleted object

I have some code that looks to see if a user belongs to an AD group. This code works unless a user from a foreign domain belongs to the group and has been deleted. When this happens the code will throw a PrincipalOperationException.

An error (1301) occurred while enumerating the groups. The group's SID could not be resolved.

public static bool IsGroupMember(string userName, string domain, string groupName)
{
    using (var pc = new PrincipalContext(ContextType.Domain, domain))
    {
        // Find a user
        UserPrincipal user = UserPrincipal.FindByIdentity(pc, userName);

        if (user == null)
            throw new InvalidUserException("User '" + userName + "' does not exist.");

        // Create MyDomain domain context
        using (var ctx = new PrincipalContext(ContextType.Domain, "MyDomain"))
        {
            // Find the group in question
            GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);

            if (group == null)
                throw new InvalidGroupException("Group '" + groupName + "' does not exist.");

            // Check if user is member of that group
            if (group.GetMembers(true).Contains(user))
                return true;
            else
                return false;
        }
    }
}

What are my options. I was hoping to filter GetMembers to remove deleted objects prior to doing the Contains but have not been successful. Do I need to back away from AccountManagement and do something more manual?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire