Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetAuthorizationGroups() is throwing exception

PrincipalContext context = new PrincipalContext(ContextType.Domain, "ipofmachine", "DC=xyz,DC=org", "username", "Password");

UserPrincipal userPrinciple = UserPrincipal.FindByIdentity(context, "User0"); 
var groups = userPrinciple.GetAuthorizationGroups();

if (userPrinciple != null)
{
    foreach (GroupPrincipal gp in groups)
    {
        //some thing
    }
}

Is there any permission that I need to give? In some of the blogs I learned that if there are no users which are set to include the SID history then this will work fine (but i think you can not edit the sid values of the groups)

like image 461
Alok Avatar asked Apr 25 '13 18:04

Alok


1 Answers

I've found there's an issue when you add a domain user to a local group, but later that domain user is deleted out of Active Directory. The state of that local group is that instead of a domain username showing up as a member, the SID is used instead.

BUT!

That SID doesn't exist in Active Directory anymore causing things to go boom.

Of course there could be many other reasons for an NoMatchingPrincipalException to pop up, so this code provides a workaround for that. It comes from a terrific post on MSDN. The code below is a modified version found here:

http://social.msdn.microsoft.com/Forums/vstudio/en-US/9dd81553-3539-4281-addd-3eb75e6e4d5d/getauthorizationgroups-fails-with-nomatchingprincipalexception

    public static IEnumerable<Principal> getAuthorizationGroups(UserPrincipal user)
    {
        PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups();
        List<Principal> ret = new List<Principal>();
        var iterGroup = groups.GetEnumerator();
        using (iterGroup)
        {
            while (iterGroup.MoveNext())
            {
                try
                {
                    Principal p = iterGroup.Current;
                    Console.WriteLine(p.Name);
                    ret.Add(p);
                }
                catch (NoMatchingPrincipalException pex)
                {
                    continue;
                }
            }
        }
        return ret;
    }
like image 188
C. Tewalt Avatar answered Nov 05 '22 17:11

C. Tewalt