如何从JNDI获取ldap数据

时间:2014-01-31 08:19:16

标签: java ldap jndi

抱歉,我是JNDI的菜鸟,我尝试使用简单的auth与JNDI连接到我的LDAPS,但我不知道连接后如何获取数据所以我的代码是:

 public static void main(String[] args) {

// Set up environment for creating initial context
Hashtable<String, String> env = new Hashtable<String, String>(11);
env.put(Context.INITIAL_CONTEXT_FACTORY, 
    "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldaps://myadress:636");

// Authenticate as S. User and password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "my BASE DN");
env.put(Context.SECURITY_CREDENTIALS, "mypass");


try {
    // Create initial context
    DirContext ctx = new InitialDirContext(env);
    // Close the context when we're done
    ctx.close();
} catch (NamingException e) {
    e.printStackTrace();
}
}

DirContext ctx = new InitialDirContext(env);`

我想获取我的树和一些数据,但是如何?...例如我的树是:

-ou=people,dc=info,dc=uni,dc=com

---ou=students
-----uid=5tey37

我如何获取uid的数据?

抱歉,我是个菜鸟,对不起我的英语

1 个答案:

答案 0 :(得分:2)

您使用特定参数调用context上的搜索。在您的示例中,您可以根据特定的uid执行上下文搜索,并获取与目录对象相对应的所有可用的attributes

下面的示例,您可能想要调整特定于您的目录的搜索和属性

// Create initial context
DirContext ctx = new InitialDirContext(env);

String searchBase = "ou=people";
SearchControls searchCtls = new SearchControls();

// Specify the search scope
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

String uid = "5tey37";
String searchFilter = " (uid=" + uid + ") ";

NamingEnumeration<?> namingEnum = ctx.search(searchBase,searchFilter, searchCtls);
while (namingEnum.hasMore()) {
    SearchResult result = (SearchResult) namingEnum.next();
    // GET STUFF
    Attributes attrs = result.getAttributes();
    System.out.println(attrs.get("uid"));
...

}
namingEnum.close();
// Close the context when we're done
ctx.close();