try
{ //Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
//Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = (String)result.Properties["cn"][0];
}
catch (Exception ex)
{
throw new Exception("Error authenticating user. " + ex.Message);
}
2 回答
当我开始研究这个主题时,我发现一切都很混乱,本教程是最好的开始之一,因为很多首字母缩略词增加了难度 . https://hynek.me/articles/ldap-a-gentle-introduction/
我会引用一个关于valildation的类似问题,但不是特别关于凭证,因为有几个与此类工作相关的代码片段 .
Validate a username and password against Active Directory?
我认为你要问的是身份验证功能
我认为发布我的整个代码只会让你感到困惑所以我会解释它的结构,并希望能让你前进并给出一个片段 .
我做的方式有很多方法如下:
公共类LdapAuthentication与方法IsAuthenticated方法传递域,用户名和密码
然后我使用DirectoryEntry DirectorySearcher查找并过滤SAMAccountName然后它取决于您的应用程序以及您要查找的内容 .
但其中大部分都在System.DirectoryServices中
这应该足以让你开始搜索并获得你需要的东西 . 祝好运!
在内部,PrincipalContext.ValidateCredentials方法将使用提供的网络凭据调用LdapConnection.Bind方法,以检查它们是否有效 . 如果绑定成功,则ValidateCredentials返回true,否则返回false .
由于LdapConnection.Bind方法使用以下属性进行修饰:
您的应用程序的身份(运行该进程和/或当前模拟的用户帐户)必须通过此权限检查才能使PrincipalContext.ValidateCredentials方法正常工作 .