【问题标题】:Query active directory to get a user's roles in .NET查询活动目录以获取用户在 .NET 中的角色
【发布时间】:2011-06-06 01:37:21
【问题描述】:

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

我尝试查询 AD 目录的原因是解决内置角色管理器 AspNetWindowsTokenRoleProvider 的问题,除非用户名与当前 Windows 身份匹配,否则它不会让您调用 Roles.GetRolesForUser(username)。

【问题讨论】:

    标签: .net active-directory ldap


    【解决方案1】:

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

    Managing Directory Security Principals in the .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
       }
    }
    

    新的 S.DS.AM 让在 AD 中与用户和组一起玩变得非常容易:

    【讨论】:

    • 我在一个简单的控制台应用程序中对此进行了测试,发现我需要添加对 System.DirectoryServices.AcccountManagement 的引用,然后才能让任何代码工作。
    【解决方案2】:

    你看过this吗?

    【讨论】:

    • @marc_s 的下一个回答为您提供了一种查看 Active Directory 组的简单方法。此答案将 AD 组映射到返回“System.Web.Security.Role”对象的只读 ActiveDirectoryMembershipProvider.RoleProvider,以及以下方法:GetRolesForUser(username)、GetUsersInRole(rolename)、GetAllRoles()、IsUserInRole(user,角色), RoleExists(角色名)
    猜你喜欢
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多