我正在尝试使用Active Directory进行身份验证。这可以正常工作,但是如何在不将错误的用户名/密码消息放入捕获块中进行身份验证?这不是不好的做法吗?我发现的许多例子都提出了建议。这甚至重要吗?
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
}
}
我尝试将捕获块放入此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();
我写了一篇关于针对广告的编程时的绩效注意事项的文章
如果您在try/catch块之外宣布搜索措施怎么办?
public void ADLogin()
{
SearchResult result = null;
try
{
DirectoryEntry root = new DirectoryEntry("LDAP://" + "domain", txtUsername.Value, txtPassword.Value);
DirectorySearcher searcher = new DirectorySearcher(root, "(sAMAccountName=" + txtUsername.Value + ")");
result = searcher.FindOne();
}
catch (Exception)
{
}
if (result != null && result.Properties["sAMAccountName"] != null)
{
//AD Login Success
FormsAuthentication.RedirectFromLoginPage(txtUsername.Value, Login1.RememberMeSet);
}
else
{
//AD Login failed
//Display Error Message
}
}
不确定为什么您认为这是不好的做法。最佳实践(不具有更多有关此代码所在位置的上下文(可能是在捕获块中登录并重新插入错误;沉默失败是一种不良习惯。