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

sun*_*ays 21 c# authentication ldap

我正在使用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();
Run Code Online (Sandbox Code Playgroud)

我能够在结果变量中得到预期的输出.
但是,如果我尝试通过在目录条目中提供密码来验证同一用户,我总是会收到以下错误.

"用户名或密码不正确."

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.
Run Code Online (Sandbox Code Playgroud)

用户名和密码适用于我要验证的用户.

任何人都可以告诉我这里我做错了什么或如何调试这个.

loo*_*ode 41

此行中的用户名,密码:

DirectoryEntry("LDAP://myserver/OU=People,O=mycompany", username, password);
Run Code Online (Sandbox Code Playgroud)

应该是具有目录查找权限的帐户.它可以是服务帐户或测试目的尝试与您自己.这不应该是您尝试进行身份验证的用户/通行证.

如果要进行身份验证,可以使用PrincipalContext使用以下步骤:

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

"serviceAcct"=域用户中具有目录查找权限的帐户."serviceAcctPass"=该服务帐户的密码.正如我所说,对于测试,您可以尝试使用自己的用户/传递上下文.

另外,请确保提供的用户名具有"domain\username"或"username @ domain"格式.

  • 从您上面发布的其他评论中读取,您的域似乎不需要经过身份验证的用户进行查找.如果是这种情况,您可以使用PrincipalContext的默认构造函数而不是user/pass构造函数. (2认同)