查询活动目录以获取用户在.NET中的角色

cbp*_*cbp 4 .net ldap active-directory

我一直在使用Linq到Active Directory,但我发现很难获得用户所属的所有角色的列表.我可以检索他们的直接组的列表,但它不是递归的.

我试图查询AD目录的原因是解决内置的角色管理器AspNetWindowsTokenRoleProvider,它不允许您调用Roles.GetRolesForUser(用户名),除非用户名与当前的Windows标识匹配.

mar*_*c_s 19

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

管理.NET Framework 3.5中的目录安全性主体

基本上,您可以定义域上下文并轻松查找AD中的用户和/或组:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

if(user != null)
{
   // find the roles....
   var roles = user.GetAuthorizationGroups();

   // enumerate over them
   foreach (Principal p in roles)
   {
       // do something
   }
}
Run Code Online (Sandbox Code Playgroud)

新的S.DS.AM使得在AD中使用用户和群组变得非常容易:

  • 我在一个简单的控制台应用程序中对此进行了测试,并发现我需要添加对“System.DirectoryServices.AcccountManagement”的引用,然后才能使任何代码工作。 (2认同)

Rob*_*Rob 1

你看过这个吗?