C# LDAP身份验证仅适用于管理员帐户

C# LDAP身份验证仅适用于管理员帐户,c#,active-directory,windows-server-2003,adldap,C#,Active Directory,Windows Server 2003,Adldap,我已经为Active directory LDAP用户身份验证编写了代码。它对AD中的所有用户帐户进行身份验证,但我只需要管理员帐户身份验证,而不需要其他用户帐户身份验证(请参阅下面的代码)。还可以查找连接DNS的域名(请参阅附件) 请尝试以下代码: public static bool ValidateCredential(string domain, string userName, string password) { using (var context

我已经为Active directory LDAP用户身份验证编写了代码。它对AD中的所有用户帐户进行身份验证,但我只需要管理员帐户身份验证,而不需要其他用户帐户身份验证(请参阅下面的代码)。还可以查找连接DNS的域名(请参阅附件)

请尝试以下代码:

    public static bool ValidateCredential(string domain, string userName, string password)
    {
        using (var context = new PrincipalContext(ContextType.Domain, domain))
        {
            using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName))
            {
                if (user == null) return false;

                using (var group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "Domain Admins"))
                {
                    if (group == null) return false;

                    foreach (var member in group.GetMembers())
                    {
                        if (member.Sid.Equals(user.Sid))
                        {
                            return context.ValidateCredentials(userName, password);
                        }
                    }
                }
            }
        }

        return false;
    }
    public static bool ValidateCredential(string domain, string userName, string password)
    {
        using (var context = new PrincipalContext(ContextType.Domain, domain))
        {
            using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName))
            {
                if (user == null) return false;

                using (var group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "Domain Admins"))
                {
                    if (group == null) return false;

                    foreach (var member in group.GetMembers())
                    {
                        if (member.Sid.Equals(user.Sid))
                        {
                            return context.ValidateCredentials(userName, password);
                        }
                    }
                }
            }
        }

        return false;
    }