我使用以下代码验证属于我们公司域的用户。这很好。
using (var entry = new DirectoryEntry(""))
{
DirectorySearcher ds = new DirectorySearcher(entry);
ds.Filter = "(|(&(objectCategory=user)(name=domainuser)))";
ds.PropertyNamesOnly = true;
ds.PropertiesToLoad.Add("name");
ds.ReferralChasing = ReferralChasingOption.None;
SearchResultCollection src = ds.FindAll();
bool isValid = false;
try
{
foreach (SearchResult sr in src)
{
DirectoryEntry de = sr.GetDirectoryEntry();
de.Password = "domainpassword";
object nativeObject = de.NativeObject;
if (nativeObject != null)
isValid = true;
break;
}
}
catch (DirectoryServicesCOMException ex) {}
return isValid;
}
实际问题是我需要在笔记本电脑中创建一个LDAP实例(MYINSTANCE),然后我需要以编程方式创建用户。我能够创建用户并迭代它们。
现在对于这些用户,我无法验证用户名和密码。
我所做的改变如下。
using (var entry = new DirectoryEntry("LDAP://MYPC:389/CN=MYINSTANCE,DC=COMPANYDOMAIN,DC=com", "domainuser", "domainpassword", AuthenticationTypes.Secure))
{
DirectorySearcher ds = new DirectorySearcher(entry);
ds.Filter = "(|(&(objectCategory=user)(name=instanceuser)))";
ds.PropertyNamesOnly = true;
ds.PropertiesToLoad.Add("name");
ds.ReferralChasing = ReferralChasingOption.None;
SearchResultCollection src = ds.FindAll();
bool isValid = false;
try
{
foreach (SearchResult sr in src)
{
DirectoryEntry de = sr.GetDirectoryEntry();
de.Password = "instancepassword";
object nativeObject = de.NativeObject;
if (nativeObject != null)
isValid = true;
break;
}
}
catch (DirectoryServicesCOMException ex) {}
return isValid;
}
答案 0 :(得分:0)
如果您使用的是.NET 3.5或更高版本,则可以使用System.DirectoryServices.AccountManagement
命名空间并轻松验证您的凭据:
// create a "principal context" - e.g. your domain (could be machine, too)
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "MYINSTANCE",
"CN=MYINSTANCE,DC=COMPANYDOMAIN,DC=com",
ContextType.SecureSocketLayer,
"domainuser", "domainpassword")
{
// validate the credentials
bool isValid = pc.ValidateCredentials("myuser", "mypassword");
}
这很简单,很可靠,它是你的100%C#托管代码 - 你还能要求什么? : - )
在这里阅读所有相关内容: