Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active Directory - Roles of a user [duplicate]

I understand how to use User.Identity and User.IsInRole

Is there a way to see all of the roles a user is in?

We have a lot of groups and some people are in a lot of groups, but I don't want to write a User.IsInRole 20+ times.

like image 996
James Wilson Avatar asked Dec 21 '22 05:12

James Wilson


1 Answers

In an Active Directory context, the Roles you refer to are really the security (or authorization) groups a user is a member of.

So if you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

  • Managing Directory Security Principals in the .NET Framework 3.5
  • MSDN docs on System.DirectoryServices.AccountManagement

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
   // find a user
   UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

   if(user != null)
   {
       // get the authorization groups - those are the "roles" 
       var groups = user.GetAuthorizationGroups();

       foreach(Principal principal in groups)
       {
           // do something with the group (or role) in question
       }
   }
}

The new S.DS.AM makes it really easy to play around with users and groups in AD!

like image 131
marc_s Avatar answered Jan 09 '23 20:01

marc_s