Search code examples
c#.netasp.net-mvcactive-directoryroleprovider

Active Directory RoleProvider - Principal.IsMemberOf throws PrincipalOperationException


I have created the following method in a custom Active Directory RoleProvider:

public override string[] GetRolesForUser(string username)
{
    ArrayList results = new ArrayList();
    using (var principalContext = new PrincipalContext(
             ContextType.Domain, null, domainContainer))
    {
        var user = UserPrincipal.FindByIdentity(
             principalContext, IdentityType.SamAccountName, username);
        foreach (string acceptibleGroup in GroupsToInclude)
        {
            GroupPrincipal adGroup = GroupPrincipal.FindByIdentity(
                 principalContext, acceptibleGroup);
            if (user.IsMemberOf(adGroup))
                results.Add(acceptibleGroup);
        }
    }
    return results.ToArray(typeof(string)) as string[];
}

It only checks against a white list of roles which are used in my application. The problem is that if the user is not a member of one of the roles, I get a PrincipalOperationException when the

if (user.IsMemberOf(adGroup))

line is executed. I would expect this to simply return `false if the user is not in the group. What is going wrong here?

EDIT: As and aside, if I call user.GetAuthorizationGroups() and attempt to loop through the results, I get a COMException - The specified directory service attribute or value does not exist.


Solution

  • Both Principal.IsMemberOf() and user.GetAuthorizationGroups() are using tokenGroups attribute to determine the group membership.

    You need to make sure the account you used to run the program is added to Builtin\Windows Authorization Access Group in order to access tokenGroups attribute.

    See this MSDN KB for more details.