2

こんにちは、ASP.NET アプリケーションで Active Directory と C# を使用しています。ユーザーがグループまたはこのサブグループに含まれている場合はブール値を取得したいと考えています。ユーザーがグループに含まれているが、このサブグループには含まれていないかどうかを取得するメソッドを作成しました:(

メソッドで再帰検索を行う方法:

ここに私のコード:

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

        }
4

1 に答える 1

7

IsMemberOfメソッドの代わりにGetMembers(Boolean)「true」を使用する必要があります。グループのすべてのメンバーを返します-ネストされていても。次に、ループを作成して、ユーザー原則が結果に含まれているかどうかを確認します。このリンクを確認してください。

追記:そのようなコードを試してください

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; 
}
于 2013-01-15T07:36:09.320 に答える