c# - 使用 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
}
}
解决方案
捕获异常并没有错。您无法控制内部的代码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:更好的性能
推荐阅读
- r - 如何用希伯来语阅读 R 中的 .doc 文件?
- php - 为不同的用户加载不同的数据库 - Laravel
- java - 收到错误“启动失败:类生成期间的一般错误:方法代码太大!”
- excel - VbA Worksheet_Change 无法识别单元格上的 DELETE 键
- mongodb - Mongoose 更新:增加一个计数器并在新日期重置为 0
- neural-network - 在 PyTorch 中实现 train 函数
- r - 使用 R 计算特定域区域的基因频率
- maven - Ubuntu 上的 NetBeans:项目的 pom.xml 文件包含无效的 xml 内容。请在继续之前修复文件
- java - 如何从整数、小数和指数部分重构数字?
- vue.js - 如何通过 HTTPS 服务 Vue 应用程序?