LDAP如何在Java中搜索/验证此LDAP [英] How do a LDAP search/authenticate against this LDAP in Java

查看:184
本文介绍了LDAP如何在Java中搜索/验证此LDAP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩LDAP和Java搜索。
这是我的LDIF导出组织简单

I am playing with LDAP and Java search. Here's my LDIF export with a simple organization

version: 1

dn: dc=example,dc=com
objectClass: organization
objectClass: dcObject
objectClass: top
dc: example
o: MyOrganization
description: Test Description

dn: ou=people, dc=example,dc=com
objectClass: organizationalUnit
objectClass: top
ou: people
description: All users in demo company

dn: cn=Johnny Doe,ou=people,dc=example,dc=com
objectClass: organizationalPerson
objectClass: person
objectClass: inetOrgPerson
objectClass: top
cn: Johnny Doe
sn: Johnny
homephone: 123-456-7890
mail: johnny@johnny.com
ou: Development
uid: jjohnny
userpassword:: johnny

dn: cn=Samuel Johnson,ou=people,dc=example,dc=com
objectClass: organizationalPerson
objectClass: person
objectClass: inetOrgPerson
objectClass: top
cn: Samuel Johnson
sn: Samuel
homephone: 123-456-7890
mail: sam@ssam.com
ou: Accounts
uid: ssam
userpassword:: sammy

如何运行Java代码段以从LDAP服务器获取所有用户?我的Apache DS Directory Server上没有设置身份验证。

How do I run a Java snippet to get all users from the LDAP server? There's no authentication set-up on my Apache DS Directory Server.

Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:10389/dc=example,dc=com");
env.put(Context.SECURITY_AUTHENTICATION, "none");

try {
    // Create initial context
    DirContext ctx = new InitialDirContext(env);
    Object obj = new Object();
    // want to print all users from the LDAP server
    System.out.println(obj.toString());
    ctx.close();
}


推荐答案

    try {
        LdapContext ctx = new InitialLdapContext(env, null);
        ctx.setRequestControls(null);
        NamingEnumeration<?> namingEnum = ctx.search("ou=people,dc=example,dc=com", "(objectclass=user)", getSimpleSearchControls());
        while (namingEnum.hasMore ()) {
            SearchResult result = (SearchResult) namingEnum.next ();    
            Attributes attrs = result.getAttributes ();
            System.out.println(attrs.get("cn"));

        } 
        namingEnum.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

private SearchControls getSimpleSearchControls() {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setTimeLimit(30000);
    //String[] attrIDs = {"objectGUID"};
    //searchControls.setReturningAttributes(attrIDs);
    return searchControls;
}

这篇关于LDAP如何在Java中搜索/验证此LDAP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆