1

I have a method to retrieve a list of AD groups that a user belongs to. Here is the code:

public static List<GroupPrincipal> GetGroups(string userName)
        {
            List<GroupPrincipal> result = new List<GroupPrincipal>();

            // establish domain context
            PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);
            UserPrincipal user = null;

            // find your user
           user = UserPrincipal.FindByIdentity(yourDomain, userName);

            // if found - grab its groups
            if (user != null)
            {
                PrincipalSearchResult<Principal> groups = user.GetGroups();   

                // iterate over all groups
                foreach (Principal p in groups)
                {
                    // make sure to add only group principals
                    if (p is GroupPrincipal)
                    {
                        result.Add((GroupPrincipal)p);
                    }
                }
            }

            return result;
        }

In both IE and Chrome, this can work fine, but in Firefox, it always gives me DirectoryServicesCOMException on the user = UserPrincipal.FindByIdentity(yourDomain, userName); I don't even have any idea what kind of exception that is. Can someone explain me what the error is and how to fix it? Thank you so much!

user2701646
  • 139
  • 4
  • 4
  • 20
  • 2
    Just as a test, try putting that line inside a `using (HostingEnvironment.Impersonate()){ ... }` call and see if that fixes it. The account that the app pool is running under will need AD access. – Pete Oct 01 '13 at 20:56
  • It works now!! Thank you!!! would you mind explaining that to me? – user2701646 Oct 01 '13 at 21:08
  • Why would it work for IE and Chrome, but not Firefox? – RobSiklos Oct 01 '13 at 21:16
  • Not too sure why, when I used IE and Chrome, it can find the user just find, but if I use firefox, it would give me the expection. – user2701646 Oct 01 '13 at 21:18
  • 1
    All 3 browsers work a little differently in how they pass their credentials to the web server. I can't remember specifically what it is about Firefox that's different, but I remember we had to accomodate it separately from other browsers... – Pete Oct 01 '13 at 21:21

1 Answers1

3

Change the call to look like this:

using (HostingEnvironment.Impersonate()){
    user = UserPrincipal.FindByIdentity(yourDomain, userName); 
}

You will need to make sure that your application pool has AD permissions. This will perform the underlying AD call using the credentials of the hosting environment (the web App Pool Identity) instead of the credentials of user, who may not have permissions to query the AD server.

Pete
  • 6,585
  • 5
  • 43
  • 69