views:

439

answers:

1

Help! I've been trying to write a function that will confirm a user's membership in an Active Directory group, and while it works if the member happens to be in the group, it throws an exception if the user is not.

Here is the function:

private bool IsUserMemberOfGroup(string user, string group)
{
  using (var ctx = new PrincipalContext(ContextType.Domain))
  using (var groupPrincipal = GroupPrincipal.FindByIdentity(ctx, group))
  using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, user))
  {
    if (groupPrincipal == null)
    {
      return false;
    }
    else
    {
      return userPrincipal.IsMemberOf(groupPrincipal);
    }
  }
}

And here is the YSOD:

Server Error in '/' Application.

Unknown error (0x80005000)

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:

System.Runtime.InteropServices.COMException: Unknown error (0x80005000)

Source Error:

 
Line 34:         else
Line 35:         {
Line 36:           return userPrincipal.IsMemberOf(groupPrincipal);
Line 37:         }
Line 38:       }

I don't know if it's related, but when I step through the function, groupPrincipal.Members.Count throws an exception of type "System.NullReferenceException", with Count.Base shows an exception with the message "Object reference not set to instance of an object".

What the heck's going on? Why won't a bool named IsMemberOf just return false when someone's not a member?

Thanks,

Daniel

+2  A: 

I think you could simplify things a bit:

private bool IsUserMemberOfGroup(string user, string group)
{
  using (var ctx = new PrincipalContext(ContextType.Domain))
  using (var userPrincipal = UserPrincipal.FindByIdentity(ctx, user))
  {
      PrincipalSearchResult<Principal> result = userPrincipal.GetGroups();

      GroupPrincipal groupPrincipal = 
           result.Where(g => g.SamAccountName == groupName).FirstOrDefault();

      return (groupPrincipal != null);
  }
}

The userPrincipal.GetGroups() will give you a definitive list of all group memberships (including primary group and nested group memberships) for that user; then search that list for the group you're interested in, e.g. by samACcountName or some other property.

If you find the group you're looking for in the PrincipalSearchResult<Principal> returned by GetGroups(), then your user is a member of that group.

You can save yourself at least one "FindByIdentity" call with this.

marc_s
Well... That works. I'm not sure why that code works and mine doesn't, but it definitely works. Strange. Thanks for the quick response!
Daniel