Extending GroupPrincipal and Members property

2019-05-24 11:45发布

I want to extend the GroupPrincipal class to handle some custom properties:

using System.DirectoryServices.AccountManagement;

[DirectoryRdnPrefix("CN")]
[DirectoryObjectClass("group")]
public class MyGroupPrincipal : GroupPrincipal {
    // ...
}

How could I override the Members property for MyGroupPrincipal so that if it has a member that is a group an instance of MyGroupPrincipal and not of GroupPrincipal is returned? I would like to write e.g.

MyGroupPrincipal group = GetGroup();
foreach (var m in group.Members) {
    if (m is MyGroupPrincipal) { // always fails: m is a normal GroupPrincipal 
        // do something
    }
}

1条回答
别忘想泡老子
2楼-- · 2019-05-24 12:22

There is no way to directly override the Members property of GroupPrincipal. Instead you can roll your own method (sorry for no clean cut code, but I've used portions of the below described solutiont through out my code).

I've found that many times with the AccountManagement library that you just have to use the base DirectoryEntry to get things done right. You can access the base object by using group.GetUnderlyingObject(), then read the membership by iterating deGroup.Properties("member"). Read each members type (can't remember the property name, maybe 'member.SchemaClassName'?) and distinguishedName (member.Properties("distinguishedName")(0).ToString()) Then create a switch statement based on type where you create each principal using the distinguished name MyGroupPrincipal.FindByIdentity(context, distinguishedName), and do the same for users, etc...

查看更多
登录 后发表回答