0

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?

Derrick Moeller
  • 4,808
  • 2
  • 22
  • 48
  • Which part of the code throws the Exception? `GetMembers()`? `Contains()`? – Mathias R. Jessen Aug 04 '15 at 15:40
  • possible duplicate of [.NET 4.5 Bug in UserPrincipal.FindByIdentity (System.DirectoryServices.AccountManagement)](http://stackoverflow.com/questions/12608971/net-4-5-bug-in-userprincipal-findbyidentity-system-directoryservices-accountma) – Mathias R. Jessen Aug 04 '15 at 15:42
  • GetMembers() throws the exception, but only when followed by Contains(), or ToList(), etc. I believe IEnumerables need to be iterated before you'll see the exception. – Derrick Moeller Aug 04 '15 at 15:42
  • Then enumerate the output from `GetMembers()` manually and handle/skip the entries that cause an exception to be thrown. One of the answers in the Duplicate I've marked mentions that your machine might not be able to locate the DNS records for the foreign domain and fails because it can't chase the foreign principal referral, fixing that might help as well – Mathias R. Jessen Aug 04 '15 at 15:47
  • Enumeration is what causes the exception, I'm not sure I understand what you're suggesting? – Derrick Moeller Aug 04 '15 at 15:53

0 Answers0