活动目录 – 用户的角色

我了解如何使用User.IdentityUser.IsInRole

有没有办法查看用户所在的所有角色?

我们有很多小组,有些人在很多小组,但我不想写User.IsInRole 20多次。

在Active Directory上下文中,您引用的角色实际上是用户所属的安全(或授权)组。

因此,如果您使用的是.NET 3.5及更高版本,则应该查看System.DirectoryServices.AccountManagement (S.DS.AM)命名空间。 在这里阅读所有相关内容:

  • 管理.NET Framework 3.5中的目录安全性主体
  • System.DirectoryServices.AccountManagement上的MSDN文档

基本上,您可以定义域上下文并在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 } } } 

新的S.DS.AM使得在AD中与用户和群组玩起来非常容易!