【问题标题】:Return a list of all Active Directory groups a user belongs to in string[ ]在 string[ ] 中返回用户所属的所有 Active Directory 组的列表
【发布时间】:2016-03-23 00:24:09
【问题描述】:

我需要返回用户所属的所有 Active Directory 组,但在 string[] 中,所以我可以在 Generic Principal 中使用结果。

我不确定是否要转换结果?请帮忙!

string[] roles = new string[] {  
helper.GetActiveDirectoryGroups(User.Identity.Name) };

GenericPrincipal principal = new GenericPrincipal(identity,roles);

 public string[] GetActiveDirectoryGroups(string userName)
    {
          //code here

    }

【问题讨论】:

  • 是的“如何在 Active Directory 中获取用户的组”很有帮助,但它会返回一个数组列表。我需要一个 string[] 来满足我的要求。有什么想法???
  • 您可以编写一个 linq 查询从 List 中获取广告组的名称。

标签: c# asp.net-mvc-3 asp.net-mvc-4 c#-4.0 active-directory


【解决方案1】:

这应该可以解决问题。

using System.DirectoryServices.AccountManagement;

public static string[] GetGroups(string username)
{
    string[] output = null;

    using (var ctx = new PrincipalContext(ContextType.Domain))
    using (var user = UserPrincipal.FindByIdentity(ctx, username))
    {
        if (user != null)
        {
            output = user.GetGroups() //this returns a collection of principal objects
                .Select(x => x.SamAccountName) // select the name.  you may change this to choose the display name or whatever you want
                .ToArray(); // convert to string array
        }
    }

    return output;
}

【讨论】:

  • 没错,大卫!正是我想要的。 ToArray() 将主体对象的集合转换为字符串数组。
  • 像魅力一样工作!
  • 除了不递归检查组外,此方法有效
  • 如果你想获取所有嵌套组而不是 GetGroups() 使用 GetAuthorizationGroups()
【解决方案2】:

如果你想在用户属于一个组的情况下返回一个布尔值,就这样吧:

 string[] output = null;
            using (var ctx = new PrincipalContext(ContextType.Domain, domain))
            using (var user = UserPrincipal.FindByIdentity(ctx, username))
            {
                if (user != null)
                {
                    output = user.GetGroups()
                        .Select(x => x.SamAccountName)
                        .ToArray();
                }

                bool isMember = output.Any(groupName.Contains);
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多