【问题标题】:Simple means to get user's roles from AD?从 AD 获取用户角色的简单方法?
【发布时间】:2012-09-28 06:29:19
【问题描述】:

我正在编写一个独立的应用程序,它需要在给定 AD 帐户名称的情况下确定用户是否是特定组的成员。我正在用 .NET (C#) 编写应用程序。 AD 中的结构如下所示:

  • 组织
    • 1 队
      • 大卫(用户)
    • 应用程序 A
      • 第 1 队 (上组)

仅列出 David 的成员身份不会表明他是 Application A 组的成员。

我从 Microsoft 的文档中了解到(使用主体)我可以简单地使用 IsInRole 调用,但我找不到任何不需要 David 登录到机器或运行执行检查的应用程序的情况。我认为我对安全模型的有限理解也在这里发挥了作用。

有人可以指出我正确的方向吗?我正在寻找的是有关如何在 C# 中解决上述问题(参考、技巧、sn-ps)的提示,而无需依赖 David 必须运行任何应用程序。

如果有什么可以澄清的,请告诉我。

【问题讨论】:

    标签: c# .net active-directory ldap


    【解决方案1】:

    添加对 DirectoryServices.AccountManagement 的引用

    然后添加 using 语句:

    using System.DirectoryServices.AccountManagement;
    

    然后在您的主过程中(或其他地方,如果需要,调用过程 IsMember:

    string userName = "David";
    string GroupName = "Team 1";
    bool test = IsMember(userName, GroupName);
    

        public static bool IsMember(string UserName, string GroupName)
        {
            try
            {
                UserPrincipal user = UserPrincipal.FindByIdentity(
                    new PrincipalContext(ContextType.Domain),
                    UserName);
    
                foreach (Principal result in user.GetAuthorizationGroups())
                {
                    if (string.Compare(result.Name, GroupName, true) == 0)
                        return true;
                }
                return false;
            }
            catch (Exception E)
            { 
                throw E; 
            }
        }
    

    如果 David 在 Team 1 中,则该过程将返回 true,否则返回 false。

    【讨论】:

    • 谢谢,GetAuthorizationGroups() 是关键。
    【解决方案2】:

    您可以使用UserPrincipal.FindByIdentity 从目录中获取UserPrincipal 对象。这与您可能找到的其他主体对象并不完全相同,但它确实有一个 IsMemberOf 方法允许您查询组成员身份。

    【讨论】:

      【解决方案3】:

      我在我的 AD 环境中使用它

      var pc = new PrincipalContext(ContextType.Domain);
      var group = GroupPrincipal.FindByIdentity(pc, "GROUPNAME");
      var existsInGroup = group.GetMembers(true).Where(p => p.UserPrincipalName == "username@domain").Any();
      

      如果您不想检查子组,请将false 传递给GetMembers

      它不需要给定的用户必须登录。希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 2018-09-03
        • 1970-01-01
        • 2019-07-18
        • 1970-01-01
        • 1970-01-01
        • 2020-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多