【发布时间】:2021-11-02 07:46:45
【问题描述】:
我正在尝试使用各种代码 sn-p 使用 LDAP 进行身份验证,但总是让 ldap 服务器不可用。 虽然当我尝试与 LDAP 浏览器连接时相同的连接,但它可以工作。 http://btechintegrator.com/index.php/2020/01/22/free-online-cloud-ldap/
知道我应该使用什么特定的 C# 代码 sn-p 来连接和验证
试过了
try
{
LdapConnection con = new LdapConnection(new LdapDirectoryIdentifier("LDAP://www.btechldap.com", 1389));
con.SessionOptions.SecureSocketLayer = true;
con.SessionOptions.VerifyServerCertificate = new VerifyServerCertificateCallback(ServerCallBack);
con.Credential = new NetworkCredential("cn=readonlybind,ou=admins,dc=btechsample,dc=com", "btechpass");
con.AuthType = AuthType.Basic;
con.Bind();
}
catch (Exception ex)
{
}
try
{
string username = "developer";
string password = "developer_pass";
string filter = "(&(&(objectclass=user)(objectcategory=person))" +
"sAMAccountName=username)";
NetworkCredential credentials = new NetworkCredential(username, password);
LdapDirectoryIdentifier directoryIdentifier =
new LdapDirectoryIdentifier("LDAP://shihadeh.intern/cn=developer,ou=admins,dc=shihadeh,dc=intern", 389, true, false);
using (LdapConnection connection =
new LdapConnection(directoryIdentifier, credentials, AuthType.Basic))
{
connection.Timeout = new TimeSpan(0, 0, 90);
connection.SessionOptions.ProtocolVersion = 3;
connection.Bind();
//SearchRequest search =
// new SearchRequest(username, filter, System.DirectoryServices.Protocols.SearchScope.Base, "mail");
//SearchResponse response = connection.SendRequest(search) as SearchResponse;
//foreach (SearchResultEntry entry in response.Entries)
//{
// Console.WriteLine(entry.Attributes["mail"][0]);
//}
}
}
catch (Exception ex)
{
}
我可以通过以下代码通过 Java 进行连接。需要等效的 .net 一个
public static void main(String[] args) {
String url = "ldap://localhost:389";
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=developer,dc=shihadeh,dc=intern");
env.put(Context.SECURITY_CREDENTIALS, "developer_pass");
try {
DirContext ctx = new InitialDirContext(env);
System.out.println("connected");
System.out.println(ctx.getEnvironment());
// do something useful with the context...
ctx.close();
} catch (AuthenticationNotSupportedException ex) {
System.out.println("The authentication is not supported by the server");
} catch (AuthenticationException ex) {
System.out.println("incorrect password or username");
} catch (NamingException ex) {
System.out.println("error when trying to create the context");
}
System.console().readLine();
}
【问题讨论】:
-
为什么在上面的例子中显示了 3 个不同的主机名?我看到
www.btechldap.com、shihadeh.intern和localhost。我认为您应该尝试使用 localhost 的 C# 示例。 -
我尝试连接两个实现。一个是运行在 127.0.0.1:389 的本地容器,域名为 shihadeh.intern。 (github.com/wshihadeh/ldap_server) 另一个是公开可用的 ldap 服务器 (btechintegrator.com/index.php/2020/01/22/free-online-cloud-ldap) 我能够从 LDAP 浏览器和 java 代码进行连接。但.net 不起作用