Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 709
M.Azad Avatar asked Feb 01 '26 20:02

M.Azad


2 Answers

In a web environment:

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

or in your context:

user.GetGroups()

MSDN

like image 85
Peter Avatar answered Feb 04 '26 09:02

Peter


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.

like image 29
Wiktor Zychla Avatar answered Feb 04 '26 09:02

Wiktor Zychla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!