Active Directory - Roles of a user [duplicate]

2020-03-06 14:37发布

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.

1条回答
唯我独甜
2楼-- · 2020-03-06 15:15

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!

查看更多
登录 后发表回答