How I can make a recursiv search in ad with a User whether this is in a group or subgroup?

寵の児 提交于 2019-12-12 22:25:15

问题


Hi I use the Active Directory and C# in a ASP.NET Application and I want that I get a bool if a User is in a Group or in this SubGroups. I have write a method that get me whether th user is in the group but not in this Subgroups :(

How I can make a recursiv search in my method:

here my code:

public static bool IsUserInGroup(string dc, string User, string group) 
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain, dc);

            GroupPrincipal p = GroupPrincipal.FindByIdentity(ctx, group);

            UserPrincipal u = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, User);

            bool isMember = u.IsMemberOf(p); 

            return isMember; 
        }

static void Main(string[] args)
        {
            string dc = "company.com";
            string user = "test.w";

            bool isadmin = IsUserInGroup(dc, user, "TAdmin");
            bool isUser = IsUserInGroup(dc, user, "TUser");

            Console.WriteLine("Admin: " + isadmin);
            Console.WriteLine("User: " + isUser);

            Console.ReadLine();

        }

回答1:


Instead of IsMemberOf method you should use GetMembers(Boolean) with 'true'. It will return all the members of the group - even nested. Then make a loop to check if your user principle is in the result. Check this link.

Additional note: try such code

public static bool IsUserInGroup(string dc, string User, string group) 
{
    bool found = false;

    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, dc);
    GroupPrincipal p = GroupPrincipal.FindByIdentity(ctx, group);
    UserPrincipal u = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, User);

    found = p.GetMembers(true).Contains(u);

    p.Dispose();
    u.Dispose();

    return found; 
}


来源:https://stackoverflow.com/questions/14332964/how-i-can-make-a-recursiv-search-in-ad-with-a-user-whether-this-is-in-a-group-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!