Расширения UserPrincipal возвращают компьютеры - PullRequest
0 голосов
/ 30 августа 2018

Я довольно плохо знаком с активным каталогом, и в настоящее время я работаю над библиотекой для проекта, который бы легко управлял объектами нашего активного каталога, такими как пользователи, ресурсы, группы и т. Д.

Библиотека находится в .NetStandard 2.0, и я использую основные классы из

System.DirectoryServices.AccountManagement

Поскольку класс UserPrincipal не содержит всех необходимых нам свойств, я попытался реализовать класс UserPrincipalExtended, который пока просто добавляет свойство Initials.

Вот мой класс:

[DirectoryObjectClass("user")]
[DirectoryRdnPrefix("CN")]
public class UserPrincipalExtended : UserPrincipal
{
    public UserPrincipalExtended(PrincipalContext context) : base(context) { }

    public UserPrincipalExtended(PrincipalContext context, string samAccountName, string password, bool enabled) : base(context, samAccountName, password, enabled) { }

    [DirectoryProperty("Initials")]
    public string Initials
    {
        get
        {
            if (ExtensionGet("initials").Length != 1) return null;

            return (string)ExtensionGet("initials")[0];

        }
        set { ExtensionSet("initials", value); }
    }

    public static new UserPrincipalExtended FindByIdentity(PrincipalContext context, string identityValue)
    {
        return (UserPrincipalExtended)FindByIdentityWithType(context, typeof(UserPrincipalExtended), identityValue);
    }

    public static new UserPrincipalExtended FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue)
    {
        return (UserPrincipalExtended)FindByIdentityWithType(context, typeof(UserPrincipalExtended), identityType, identityValue);
    }
}

Когда я выполняю поиск в активном каталоге с использованием класса UserPrincipal, он работает как положено:

using (var context = _contextProvider.GetPrincipalContext())
using (var query = new UserPrincipal(context))
using (var searcher = new PrincipalSearcher(query))
{
    foreach (var principal in searcher.FindAll())
    {
        UserPrincipal userPrincipal = principal as UserPrincipal;

        if (CheckHelper.IsFilled(userPrincipal))
        {
            Console.WriteLine($"{userPrincipal.StructuralObjectClass} : {userPrincipal.SamAccountName}");
        }
    }
}

/*Output
user : cadmin
user : Guest
user : DefaultAccount
*/

Но если я попытаюсь выполнить тот же поиск, используя свой собственный класс, в результате появятся также компьютеры:

using (var context = _contextProvider.GetPrincipalContext())
using (var query = new UserPrincipalExtended(context))
using (var searcher = new PrincipalSearcher(query))
{
    foreach (var principal in searcher.FindAll())
    {
        UserPrincipalExtended userPrincipalExtended = principal as UserPrincipalExtended;

        if (CheckHelper.IsFilled(userPrincipalExtended))
        {
            Console.WriteLine($"userPrincipalExtended.StructuralObjectClass} : {userPrincipalExtended.SamAccountName}");
        }
    }
}
/*Output
user : cadmin
user : Guest
user : DefaultAccount
computer : WS001$
computer : WS002$
computer : WS003$
*/

Поскольку мой класс UserPrincipalExtended имеет атрибут:

[DirectoryObjectClass("user")]

Я подумал, что этого достаточно для фильтрации этого типа объектов в активной директории, но, похоже, этого не происходит.

Есть идеи, что здесь происходит?

Приветствия

1 Ответ

0 голосов
/ 27 января 2019

Майкрософт Фильтр основных типов, создающий код

Тоже столкнулся с этой проблемой. Порывшись в исходном коде, нашел такой обходной путь.

[DirectoryObjectClass ( "пользователь) (ObjectCategory = пользователь")]

...