简体   繁体   English

使用C#根据LDAP对用户进行身份验证

[英]Using C# to authenticate user against LDAP

I'm using DirectorySearcher to search for a user entry in LDAP server. 我正在使用DirectorySearcher在LDAP服务器中搜索用户条目。

DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://myserver/OU=People,O=mycompany";
de.AuthenticationType = AuthenticationTypes.None;

DirectorySearcher deSearch = new DirectorySearcher();

deSearch.SearchRoot = de;
deSearch.Filter = "(uid=" + model.UserName + ")";

SearchResult result = deSearch.FindOne();

I'm able to get th intended output in result variable. 我能够在结果变量中得到预期的输出。
However If I try to authenticate the same user by providing password in directory entry, I always get following error. 但是,如果我尝试通过在目录条目中提供密码来验证同一用户,我总是会收到以下错误。

"The user name or password is incorrect." “用户名或密码不正确。”

DirectoryEntry entry = new DirectoryEntry("LDAP://myserver/OU=People,O=mycompany", username, password);
DirectorySearcher search = new DirectorySearcher(
    entry,
    "(uid=" + username + ")",
    new string[] { "uid" }
);

search.SearchScope = System.DirectoryServices.SearchScope.Subtree;
SearchResult found = search.FindOne();   ->>>>>this is where I get wrong credential error.

The username and password are for the user I want to authenticate. 用户名和密码适用于我要验证的用户。

Can anyone tell me what I'm doing wrong here or how to debug this. 任何人都可以告诉我这里我做错了什么或如何调试这个。

This username, password within this line: 此行中的用户名,密码:

DirectoryEntry("LDAP://myserver/OU=People,O=mycompany", username, password);

should be for an account that has permission for directory lookup. 应该是具有目录查找权限的帐户。 It could be a service account or testing purpose try with your own. 它可以是服务帐户或测试目的尝试与您自己。 This shouldn't be the user/pass of someone who you are trying to authenticate. 这不应该是您尝试进行身份验证的用户/通行证。

If you want to authenticate, you can use following steps using PrincipalContext: 如果要进行身份验证,可以使用PrincipalContext使用以下步骤:

using(var context = new PrincipalContext(ContextType.Domain, "mydomain", "mydomain\serviceAcct", "serviceAcctPass")) {
 //Username and password for authentication.
 return context.ValidateCredentials(username, password); 
}

"serviceAcct" = an account within domain users that has permission for directory lookup. “serviceAcct”=域用户中具有目录查找权限的帐户。 "serviceAcctPass" = password for that service account. “serviceAcctPass”=该服务帐户的密码。 As I said, for testing you can try with your own user/pass context. 正如我所说,对于测试,您可以尝试使用自己的用户/传递上下文。

Also, make sure supplied username has either "domain\\username" or "username@domain" formatting. 另外,请确保提供的用户名具有“domain \\ username”或“username @ domain”格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM