如何在 Java 中对此 LDAP 进行 LDAP 搜索/认证

2022-09-01 09:08:35

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

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 上没有身份验证设置。

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();
}

答案 1

另一种方法是使用UnboundID。它的api非常可读且更短

创建 Ldap 连接

public static LDAPConnection getConnection() throws LDAPException {
    // host, port, username and password
    return new LDAPConnection("com.example.local", 389, "Administrator@com.example.local", "admin");
}

获取筛选结果

public static List<SearchResultEntry> getResults(LDAPConnection connection, String baseDN, String filter) throws LDAPSearchException {
    SearchResult searchResult;

    if (connection.isConnected()) {
        searchResult = connection.search(baseDN, SearchScope.ONE, filter);

        return searchResult.getSearchEntries();
    }

    return null;
}

获取所有认证单位和容器

String baseDN = "DC=com,DC=example,DC=local";
String filter = "(&(|(objectClass=organizationalUnit)(objectClass=container)))";

LDAPConnection connection = getConnection();        
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

获取特定组织单位

String baseDN = "DC=com,DC=example,DC=local";
String dn = "CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(|(objectClass=organizationalUnit)(objectClass=container))(distinguishedName=%s))";
String filter = String.format(filterFormat, dn);

LDAPConnection connection =  getConnection();

List<SearchResultEntry> results = getResults(connection, baseDN, filter);

获取单位部门下的所有用户

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String filter = "(&(objectClass=user)(!(objectCategory=computer)))";

LDAPConnection connection =  getConnection();       
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

获取组织单位下的特定用户

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String userDN = "CN=abc,CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(objectClass=user)(distinguishedName=%s))";
String filter = String.format(filterFormat, userDN);

LDAPConnection connection =  getConnection();
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

显示结果

for (SearchResultEntry e : results) {
    System.out.println("name: " + e.getAttributeValue("name"));
}

答案 2
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;
}

推荐