Подтвердить что ты не робот

Получите родительский OU пользователя в Active Directory с помощью С#

Я хочу проверить, если пользователь aa находится в определенном родительском подразделении.

Как я могу это сделать?

Проверьте ниже код для четкого описания того, что я ищу.

using System.DirectoryServices.AccountManagement;

public bool IsUserInOU(string samAccountName, string OUName){

    using (var context = new PrincipalContext(ContextType.Domain))
        {
            using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, samAccountName))
            {                    
                //Check if the user is in the OU specified in OUName
                //Something like:
                //return user.IsInOU(OUName);
            }
         }
}

public void TestIt_1(){
  //The parent OU of this user is "AwesomeOU"
  string samAccountName = "Joe";
  string OUName = "AwesomeOU";
  bool expected = true;
  bool actual = IsUserInOU(samAccountName, OUName);
  Assert.AreEqual(expected, actual);
}

public void TestIt_2(){
  //The parent OU of this user is "WhateverOU"
  string samAccountName = "Mike";
  string OUName = "AwesomeOU";
  bool expected = false;
  bool actual = IsUserInOU(samAccountName, OUName);
  Assert.AreEqual(expected, actual);
}

Домен:

  • Национальный OU
    • Awesome OU
      • Джо
    • Независимо от OU
      • Майк

Решение 1 после ответа empi

С информацией, предоставленной empi, я написал метод ниже, чтобы извлечь первое подразделение в DistinguishedName. Сделав это, остальное - легкий ветерок.

public static string GetOUForUser(string samAccountName)
    {
        using (var context = new PrincipalContext(ContextType.Domain))
        {
            using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, samAccountName))
            {
                //System.Console.WriteLine(user.DistinguishedName);
                int startIndex = user.DistinguishedName.IndexOf("OU=", 1) + 3; //+3 for  length of "OU="
                int endIndex = user.DistinguishedName.IndexOf(",", startIndex);
                var group = user.DistinguishedName.Substring((startIndex), (endIndex - startIndex));
                return group;
            }
        }
    }

Решение 2 после ответа JPBlanc

public static string GetOUForUser(string samAccountName)
    {
        using (var context = new PrincipalContext(ContextType.Domain))
        {
            using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, samAccountName))
            {
                using (DirectoryEntry deUser = user.GetUnderlyingObject() as DirectoryEntry)
                {
                    using (DirectoryEntry deUserContainer = deUser.Parent)
                    {
                        return deUserContainer.Properties["Name"].Value.ToString();
                    }
                }
            }
        }
    }
4b9b3361

Ответ 1

Решение Ok @Empi работает, но UserPrincipal построен на объектах DirectoryEntry который предоставляет parent или container свойства, которые просто дают вам объект, который вы ищете, без использования строкового способа.

/* Retreiving a principal context
 */
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "WM2008R2ENT:389", "dc=dom,dc=fr", "dom\\jpb", "MyPwd");

/* Retreive a user
 */
UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, "user1");

/* Retreive the container
 */
DirectoryEntry deUser = user.GetUnderlyingObject() as DirectoryEntry;
DirectoryEntry deUserContainer = deUser.Parent;
Console.WriteLine (deUserContainer.Properties["distinguishedName"].Value);

Ответ 2

Эта информация находится в UserPrincipal.DistinguishedName. Вы должны проверить, заканчивается ли DistinguishedName символом "," + ou (нечувствительным к регистру). Тем не менее, вы должны знать раздутое имя, которое вы проверяете.

Например, если dn: CN=Jeff Smith,OU=Sales,DC=Fabrikam,DC=COM, тогда он говорит, что пользователь находится в OU=Sales,DC=Fabrikam,DC=COM ou.

Ответ 3

Вот как я мог бы получить Отличительное имя для конкретного пользователя AD, надеюсь, это поможет :-)

private static string GetDNOfUser(string user)
{
    var ctx = new PrincipalContext(ContextType.Domain, Environmentals.Domain, Environmentals.OUPath);

    //Creating object for search filter
    UserPrincipal userPrin = new UserPrincipal(ctx)
    {
        //Only getting users with the same name as the input
        Name = user
    };

    var searcher = new PrincipalSearcher
    {
        //Applying filter to query
        QueryFilter = userPrin
    };

    //Finding the user
    var results = searcher.FindOne();
    searcher.Dispose();

    //Return the distinguishedname
    return results.DistinguishedName;
}