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.
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:
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With