Ласкаво просимо до dev.net.ua Увійти | Приєднатися | Допомога

Ivan Bilokon

This blog is about my findings
userPrincipal.GetAuthorizationGroups(). An error occurred while enumerating the groups. The group could not be found.

Hello!

Today I struggled a bit with weird issue trying to enumerate Active Directory groups for some user. The code I used is below

using (var principalContext = new PrincipalContext(ContextType.Domain))

 {
using (var userPrincipal = UserPrincipal.FindByIdentity(principalContext, System.DirectoryServices.AccountManagement.IdentityType.SamAccountName, userLogin))
{
if (userPrincipal != null)
{
using (var groups = userPrincipal.GetAuthorizationGroups())
{
result = groups.Select(g => g.Sid.ToString()).ToArray();
}
}
}

For the user this code throws NoMatchingPrincipalException exception  in the line



result = groups.Select(g => g.Sid.ToString()).ToArray();

The cause of the error was some group that was located in container where my account didn't have read access. Weird that the group was actually listed in the collection but attempt to refer it failed with exception.

Below is my workaround. Instead of groups.Select(g => g.Sid.ToString()).ToArray(); or foreach... I wrote

var sids = new List<string>();                  

 var enumerator = groups.GetEnumerator();
///foreach does not work in cases when group is located in container where the app pool account does not have read permissions
///In this case enumerator.Current throws NoMatchingPrincipalException
while (enumerator.MoveNext())
{
try
{
var g = enumerator.Current;
sids.Add(g.Sid.ToString());
}
catch (NoMatchingPrincipalException)
{
}
}

Hope that will help somebody.

Posted: Thursday, March 5, 2015 5:35 PM від Ivan Bilokon

Коментарі

Немає коментарів

Анонімні коментарі деактивовані. Увійдіть або Зареєструйтесь щоб мати доступ до ресурсів Спільноти.