简体   繁体   English

使用C#在Active Directory中获取用户的父OU

[英]Get parent OU of user in Active Directory using C#

I want to check, if aa user is in a specific parent OU. 我想检查一个用户是否在特定的父OU中。

How can I do that? 我怎样才能做到这一点?

Check below code for a clear desciption of what I am looking for. 检查下面的代码,明确说明我在寻找什么。

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

The Domain: 域名:

  • National OU 国家OU
    • Awesome OU 很棒的OU
      • Joe
    • Whatever OU 无论什么OU
      • Mike 麦克风

Solution 1 after empi's answer 在empi回答后的解决方案1

With the information given by empi, I wrote the below method to extract the first OU in the DistinguishedName. 使用empi提供的信息,我编写了以下方法来提取DistinguishedName中的第一个OU。 Having done that, the rest is a breeze. 完成后,其余的都是轻而易举的。

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;
            }
        }
    }

Solution 2 after JPBlanc's answer 解决方案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();
                    }
                }
            }
        }
    }

Ok @Empi solution is working, but UserPrincipal is built on DirectoryEntry objects that provides a parent or container properties that just give you the object you are looking for, without using string way. 好的@Empi解决方案正在运行,但UserPrincipal是基于DirectoryEntry对象构建的,它提供了parentcontainer属性,只提供了您正在寻找的对象,而不使用字符串方式。

/* 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);

This information is in UserPrincipal.DistinguishedName . 此信息位于UserPrincipal.DistinguishedName中 You should check if DistinguishedName ends with "," + ou distinguished name (case insensitive). 您应该检查DistinguishedName是否以“,”+ ou可分辨名称(不区分大小写)结尾。 However, you must know the distingushed name of ou you're checking. 但是,您必须知道您正在检查的名字。

For example, if dn is: CN=Jeff Smith,OU=Sales,DC=Fabrikam,DC=COM , then it says that user is in OU=Sales,DC=Fabrikam,DC=COM ou. 例如,如果dn是: CN=Jeff Smith,OU=Sales,DC=Fabrikam,DC=COM ,则表示用户在OU=Sales,DC=Fabrikam,DC=COM ou。

This is how I would get the Distinguished Name for a specific AD user, hope it helps :-) 这就是我如何获得特定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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM