LDAP通过JAVA而不提供密码

时间:2016-05-30 10:48:30

标签: java c# ldap

在C#中,我写了下面的代码来连接到LDAP服务器并查询相同的内容。

String ldapUrl = "LDAP://...";
            DirectoryEntry entry = new DirectoryEntry(ldapUrl);
            DirectorySearcher dSearch = new DirectorySearcher(entry);

            String Name = "ravi";
            dSearch.Filter = "(&(objectClass=user)(sAMAccountName=" + Name + "))";

            foreach (SearchResult sResultSet in dSearch.FindAll())
            {
                String data =  "Login Name :" + (GetProperty(sResultSet, "cn")) + "\r\n" +
                    "First Name :" + (GetProperty(sResultSet, "givenName")) + "\r\n" +
                    "Middle Initials :" + (GetProperty(sResultSet, "initials")) + "\r\n" +
                    "Last Name : " + (GetProperty(sResultSet, "sn"));
            }

如果您注意到,我没有提供用户名和/或密码。我认为它使用登录用户凭据的操作系统登录LDAP服务器。

但是在JAVA中

String url = "ldap://localhost:10389";
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, "uid=admin,ou=system"***);
env.put(***Context.SECURITY_CREDENTIALS, "secret"***);

try {
    DirContext ctx = new InitialDirContext(env);
    System.out.println("connected");
    System.out.println(ctx.getEnvironment());

    ctx.close();

} catch (Exception ex) {
    System.out.println("error when trying to create the context");
}

java中是否有一种方法可以在不提供用户名和密码的情况下绑定到LDAP服务器?我通过将Context.SECURITY_AUTHENTICATION设置为NONE来尝试绑定,但是它们会抛出匿名登录的例外,不允许。我不知道如何使用匿名用户凭据,但操作系统已登录用户凭据。

这可能吗?如何?

此致

2 个答案:

答案 0 :(得分:0)

我使用JNI来调用C#dll ...问题是JNI非常慢。每次通话大约需要15-20秒

答案 1 :(得分:0)

使用{@ {3}}中的::在Java中使用命令行(cmd)

import com4j.Variant;
import com4j.typelibs.ado20.ClassFactory;
import com4j.typelibs.ado20._Command;
import com4j.typelibs.ado20._Connection;
import com4j.typelibs.ado20._Recordset;

public static void queryADForComputers() throws Exception{

    String query            = "cn,sn,givenName,department";
    String filter           = "(&(objectclass=user)(objectcategory=person))";
    String namingContext    = "OU=Desktops,OU=Workstations,OU=HO,DC=win";
    _Connection conn        = ClassFactory.createConnection();

    conn.provider("ADsDSOObject");
    conn.open("Active Directory Provider","","",-1);

    _Command cmd            = ClassFactory.createCommand();
    cmd.activeConnection(conn);
    cmd.commandText("<LDAP://" + namingContext + ">;" + filter + ";" + query + ";subTree");
    _Recordset rs = cmd.execute(null, Variant.getMissing(), -1);
    System.out.println("Found " + rs.recordCount() + " users/computers/whatever i was looking for");

//Then here you can use a while loop while(!rs.eof())
//in which you can get each value as rs.fields().item(i).value();
//in my case, i did rs.fields().item(i).value().toString()
//or you can check for its type and go from there. 
}