I ran into the following error while traversing certain user’s security groups in Active Directory:

System.DirectoryServices.AccountManagement.NoMatchingPrincipalException: An error occurred while enumerating the groups. The group could not be found.

The error was thrown when calling GetAuthorizationGroups() on line 3:

PrincipalContext adServer = new PrincipalContext(ContextType.Domain, CasRolesConfig.ADServer);
UserPrincipal adUser = UserPrincipal.FindByIdentity(adServer, samAccountName );
PrincipalSearchResult<Principal> adAuthGroups = adUser.GetAuthorizationGroups();
foreach (Principal adAuthGroup in adAuthGroups)
{
    string groupName = adAuthGroup.Name;
    // [...]
}

The error occurs when the group or child group contains a ForeignSecurityPrincipal. Microsoft has confirmed it as an issue and a bug has been raised internally.

As a workaround, I was able to accesss the security groups with the following code:

DirectoryEntry searchRoot = new DirectoryEntry();
searchRoot.Path = "LDAP://" + SecConfig.ActiveDirectoryServer;
searchRoot.AuthenticationType = AuthenticationTypes.Secure;

DirectorySearcher adSearcher = new DirectorySearcher();
adSearcher.SearchRoot = searchRoot;
adSearcher.Filter = "(samAccountName=" + samAccountName + ")";
adSearcher.PropertiesToLoad.Add("memberOf");

SearchResult samResult = adSearcher.FindOne();

if (samResult != null)
{
    DirectoryEntry adAccount = samResult.GetDirectoryEntry();
    foreach (String groupMembership in adAccount.Properties["memberOf"])
    {
        string groupName = groupMembership;
        // [...]
    }
}