在string []中返回用户所属的所有Active Directory组的列表

时间:2015-12-16 18:16:05

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

我需要返回用户所属的所有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

    }

2 个答案:

答案 0 :(得分:9)

这应该可以解决问题。

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;
}

答案 1 :(得分:0)

如果您想要返回bool值,如果用户属于某个组,请转到:

 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);
            }