使用LDAP路径获取Principal Context对象

时间:2016-03-14 06:35:39

标签: c# asp.net active-directory .net-4.5

我正在开发一个模块,我需要获取Active Directory组的成员。此功能已存在于项目中,但它是为.Net3.5构建的。这同样适用于.Net4.5。经过一些谷歌搜索后,我发现我需要使用“Principal Context”对象来获取Directory条目对象。

这里的问题是,我需要在Test AD中进行测试,这与我的生产AD不同。 我使用的旧方法是允许我指定测试AD服务器路径,

DirectoryEntry entry = new DirectoryEntry(ADLdapPath, ADAdminUser, ADAdminPassword, AuthenticationTypes.Secure);

任何人都可以帮我找到一种在创建“Principal Context”时指定LDAP路径(AD服务器路径)的方法,以便我可以在Test环境中进行测试。

1 个答案:

答案 0 :(得分:0)

我使用了以下帮助器(已修改),它是我的AD工具带的一部分,用于创建PrincipalContext以使用AD。这应该让你开始。修改它以满足您的需求。希望它有所帮助。

public class ADHelper {
    public static PrincipalContext CreatePrincipalContext(string domain = null) {
        string container = null;
        if (IsNullOrWhiteSpace(domain)) {
            domain = GetCurrentDnsSuffix();
            if (domain != null && domain.EndsWith(".com", StringComparison.InvariantCultureIgnoreCase)) {
                container = GetContainers(domain);
            } else {
                domain = null;
            }
        }

        var hostName = GetHostName();
        if (IsNullOrWhiteSpace(domain)) {
            domain = hostName;
        }

        ContextType contextType;
        if (domain.Equals(hostName, StringComparison.InvariantCultureIgnoreCase) &&
            domain.Equals(Environment.MachineName, StringComparison.InvariantCultureIgnoreCase)) {
            contextType = ContextType.Machine;
        } else {
            contextType = ContextType.Domain;
        }

        PrincipalContext principalContext = null;
        if (contextType == ContextType.Machine) {
            principalContext = new PrincipalContext(contextType, domain);
        } else {
            principalContext = new PrincipalContext(contextType, domain, container, Constants.LDAPUser, Constants.LDAPPassword);
        }

        return principalContext;
    }

    public static string GetCurrentDnsSuffix() {
        string dnsHostName = null;
        if (NetworkInterface.GetIsNetworkAvailable()) {
            var nics = NetworkInterface.GetAllNetworkInterfaces()
                .Where(ni => ni.OperationalStatus == OperationalStatus.Up);

            foreach (var ni in nics) {
                var networkConfiguration = ni.GetIPProperties();

                var dnsSuffix = networkConfiguration.DnsSuffix;
                if (dnsSuffix != null) {
                    dnsHostName = dnsSuffix;
                    break;
                }

                var address = networkConfiguration.DnsAddresses.FirstOrDefault();
                if (address != null) {
                    try {
                        var dnsHost = Dns.GetHostEntry(address.ToString());
                        dnsHostName = dnsHost.HostName;
                    } catch (System.Net.Sockets.SocketException e) {
                        traceError(e);
                    } catch (Exception e) {
                        traceError(e);
                    }
                }
            }
        }
        return dnsHostName;
    }

    private static string GetContainers(string ADServer) {
        string[] LDAPDC = ADServer.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
        for (int i = 0; i < LDAPDC.GetUpperBound(0) + 1; i++) {
            LDAPDC[i] = string.Format("DC={0}", LDAPDC[i]);
        }
        String ldapdomain = Join(",", LDAPDC);
        return ldapdomain;
    }
    public static string GetHostName() {
        var ipProperties = IPGlobalProperties.GetIPGlobalProperties();
        return ipProperties.HostName;
    }
}

然后我可以在这样的事情中使用它

public static List<string> GetAllUserNames(string domain = null) {
    List<string> userNames = new List<string>();
    using (var principalContext = createPrincipalContext(domain)) {
        //Get a list of user names in MyDomain that match filter
        using (UserPrincipal userPrincipal = new UserPrincipal(principalContext)) {
            using (PrincipalSearcher principalSearcher = new PrincipalSearcher(userPrincipal)) {

                var results = principalSearcher
                    .FindAll()
                    .Where(c =>
                        (c is UserPrincipal) &&
                        (c as UserPrincipal).Enabled.GetValueOrDefault(false) &&
                        !string.IsNullOrEmpty(c.DisplayName)
                        );
                foreach (UserPrincipal p in results) {
                    var temp = p.StructuralObjectClass;
                    string value = string.Format("{0} ({1})", p.DisplayName, p.EmailAddress ?? Join("\\", p.Context.Name, p.SamAccountName));
                    userNames.Add(value);
                }
            }
        }
    }
    return userNames;
}