首页 > 解决方案 > 使用 Active Directory 对用户进行身份验证,而不在 catch 块内放置不正确的用户名或密码错误

问题描述

我正在尝试使用 Active Directory 进行身份验证。这很好用,但是如何在不将不正确的用户名/密码消息放在 catch 块中的情况下进行身份验证?这不是坏习惯吗?我发现很多例子都有这个建议。这还重要吗?

public void ADLogin()
{
    try
    {
        DirectoryEntry root = new DirectoryEntry("LDAP://" + "domain", txtUsername.Value, txtPassword.Value);
        DirectorySearcher searcher = new DirectorySearcher(root, "(sAMAccountName=" + txtUsername.Value + ")");
        SearchResult result = searcher.FindOne();
        if (result.Properties["sAMAccountName"] != null)
        {
            //AD Login Success        
            FormsAuthentication.RedirectFromLoginPage(txtUsername.Value, Login1.RememberMeSet);
        }
    }
    catch (Exception)
    {
            //AD Login failed         
            //Display Error Message
    }            
}

我尝试将 catch 块放在这个 if 语句中,但它在到达它之前抛出了一个异常:

public void ADLogin()
{
    DirectoryEntry root = new DirectoryEntry("LDAP://" + "domain", txtUsername.Value, txtPassword.Value);
    DirectorySearcher searcher = new DirectorySearcher(root, "(sAMAccountName=" + txtUsername.Value + ")");
    SearchResult result = searcher.FindOne();
    if (result.Properties["sAMAccountName"] != null)
    {
        //AD Login Success        
        FormsAuthentication.RedirectFromLoginPage(txtUsername.Value, Login1.RememberMeSet);
    }
    if (result.Properties["sAMAccountName"] == null)
    {
        //AD Login failed         
        //Display Error Message
    }            
}

标签: c#asp.netactive-directory

解决方案


捕获异常并没有错。您无法控制内部的代码DirectorySearcher,因此如果出现问题,您会情不自禁地抛出异常。但是,您可能希望区分抛出的异常类型,以便区分错误的凭据和网络错误。

请注意,如果凭据错误,则会引发异常searcher.FindOne(),因为您正在使用用户的凭据连接到 AD。

这不是验证凭据的最快方法。如果你想要性能更好的东西,你可以使用这里LdapConnection的解决方案。它只是使用用户的凭据执行 LDAP 绑定,而不像您的代码那样进行搜索。如该答案所述,它还有一个额外的好处是能够告诉您身份验证失败的原因。

如果您确实需要从用户帐户中查找信息,那么是的,您需要搜索它。但是您应该使用该DirectorySearcher.PropertiesToLoad集合。如果您没有另外指定,DirectorySearcher将检索每个结果具有值的每个属性。这可能是您不需要的大量数据(尤其是如果您的组织将用户照片存储在 AD 中)。相反,您可以告诉DirectorySearcher您需要哪些属性,它只会检索那些:

DirectorySearcher searcher = new DirectorySearcher(root, "(sAMAccountName=" + txtUsername.Value + ")");
searcher.PropertiesToLoad.Add("sAMAccountName");
result = searcher.FindOne();

我写了一篇关于针对 AD 编程时的性能注意事项的整篇文章,您可能会觉得有趣:Active Directory:更好的性能


推荐阅读