M.Azad
M.Azad

Reputation: 3763

How to get the groups of a user in Active Directory?

I use from this code:

   List<GroupPrincipal> result = new List<GroupPrincipal>();

   // establish domain context
   PrincipalContext MyDomain = new PrincipalContext(ContextType.Domain);

   // find your user
   UserPrincipal user = UserPrincipal.FindByIdentity(MyDomain , username);

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

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

but on this line ( user.GetAuthorizationGroups() ) I got an exception

This server is not operational

Upvotes: 3

Views: 3370

Answers (6)

user3087556
user3087556

Reputation: 1

One of the groups your trying to grab included in the GetGroups is an administrator group and requires special permission. Try setting a user/password in your context and use getGroups(context)

Upvotes: 0

M.Azad
M.Azad

Reputation: 3763

I install my Active Directory again and my problem resolved...

Upvotes: 0

JPBlanc
JPBlanc

Reputation: 72680

I've got exactly the same trouble when I run one of my program from a computer (dev computer) which does not belong to the domain I query for. I mean that I got the context, I got the UserPrincipal information and I've got the same error when I call GetGroups(). The same program run on the server itself works perfectly.

I tryed to manage to have my developpment computer directly configured with the domain DNS as first DNS, but it was the same.

I tryed to hard configure domain and DC adresses in hosts file but it was the same.

So I remote debug my program from a virtual machine which was in the domain.

Upvotes: 0

Nasser Hadjloo
Nasser Hadjloo

Reputation: 12630

Check this if it can help you http://support.microsoft.com/kb/842789

Update :

Open Visual Studio As Administrator and then open your solution. then try again. I believe that your problem is because of application permition.

Upvotes: 1

Wiktor Zychla
Wiktor Zychla

Reputation: 48314

From what I remember, the exception can be caused by the fact that the domain name cannot be resolved with any available DNS. Make sure that it is and the exception goes away.

Upvotes: 1

Peter
Peter

Reputation: 27944

In a web environment:

System.Web.HttpContext.Current.Request.LogonUserIdentity.Groups

or in your context:

user.GetGroups()

MSDN

Upvotes: 1

Related Questions