Mozilla LDAP SDK Programmer's Guide/Writing an LDAP Client With LDAP Java SDK

From MozillaWiki
Jump to: navigation, search

This section describes the general process of writing an LDAP client. The section covers the procedures for connecting to an LDAP server, and also authentication, requesting operations, and disconnecting from the server.

Designing an LDAP Java Client

The following steps outline the typical process of communicating with an LDAP server. Follow these steps when writing your LDAP client.

  • Create a new LDAPConnection object, and set any preferences that you want applied to all LDAP operations.
  • Connect to an LDAP server.
  • If necessary, bind to the LDAP server, specifying the version of LDAP supported by your client.
  • Perform the LDAP operations, such as searching the directory or modifying entries in the directory.
  • When finished performing operations, disconnect from the LDAP server.

The following example LDAP client follows these steps to search a directory. The client connects to the LDAP server running on the local host at port 389. The client then searches the directory for entries with the surname Jensen. Finally, the client displays the DNs of matching entries.

import netscape.ldap.*;
import java.util.*;
 
public class Search {
    public static void main(String[] args) {
        try {
            UserArgs userArgs = new UserArgs("Search", args, false);
            LDAPConnection ld = new LDAPConnection();
            ld.connect(userArgs.getHost(), userArgs.getPort());
 
            /* search for all entries with surname of Jensen */
            String MY_FILTER = "sn=Jensen";
            String MY_SEARCHBASE = "dc=example,dc=com";
 
            LDAPSearchConstraints cons = ld.getSearchConstraints();
            /* Setting the batchSize to one will cause the result
               enumeration below to block on one result at a time,
               enabling an update of a list or other things as
               results come in. */
            /* This could be set to 0 in order to get all
               results and to block until then. */
            cons.setBatchSize(1);
            LDAPSearchResults res = ld.search(MY_SEARCHBASE,
                LDAPConnection.SCOPE_SUB, MY_FILTER, null, false, cons);
 
            /* Loop on results until finished */
            while (res.hasMoreElements()) {
                LDAPEntry findEntry = null;
                try {
                    findEntry = res.next();
                } catch (LDAPReferralException e) {
                    System.out.println("Search reference: ");
                    LDAPUrl refUrls[] = e.getURLs();
                    for (int i=0; irefUrls.length; i++) {
                        System.out.println("\t" + refUrls[i].getUrl());
                    }
                    continue;
                } catch (LDAPException e) {
                    System.out.println("Error: " + e.toString());
                    continue;
                }
                System.out.println(findEntry.getDN());
 
                /* Get the attributes of the entry */
                LDAPAttributeSet findAttrs = findEntry.getAttributeSet();
                Enumeration enumAttrs = findAttrs.getAttributes();
                System.out.println("\tAttributes: ");
 
                /* Loop on attributes */
                while (enumAttrs.hasMoreElements()) {
                    LDAPAttribute anAttr =
                        (LDAPAttribute)enumAttrs.nextElement();
                    String attrName = anAttr.getName();
                    System.out.println("\t\t" + attrName);
 
                    /* Loop on values for this attribute */
                    Enumeration enumVals = anAttr.getStringValues();
                    if (enumVals != null) {
                        while (enumVals.hasMoreElements()) {
                            String aVal = (String)enumVals.nextElement();
                            System.out.println("\t\t\t" + aVal);
                        }
                    }
                }
            }
            ld.disconnect();
        } catch(LDAPException e) {
            System.out.println("Error: " + e.toString());
        }
    }
}

Creating a Connection and Setting Preferences With LDAP Java SDK

The first step in writing an LDAP client is creating an LDAPConnection object. This object represents the connection to an LDAP server.

LDAPConnection ld = new LDAPConnection();

Note: If you plan to connect to the LDAP server over the Secure Sockets Layer (SSL) protocol, you need to specify a class that implements SSL sockets. Refer to SSL Connections With LDAP Java SDK for details.

The LDAPConnection object also contains preferences for the LDAP session, such as whether referrals are or are not followed automatically.

To get or set the value of a preference, invoke the getOption method or the setOption method as described in the API specification.

Connecting to an LDAP Server With LDAP Java SDK

To connect to an LDAP server, use the connect method of the LDAPConnection object.

LDAPConnection ld = new LDAPConnection();
ld.connect("ldap.example.com", LDAPv3.DEFAULT_PORT);

DEFAULT_PORT specifies the default LDAP port, port 389. You can also specify a list of LDAP servers to attempt to connect to. If the first LDAP server in the list does not respond, the client attempts to connect to the next server in the list.

Use a space-delimited list of the host names as the first argument of the connect method. If the server is not using the default LDAP port, specify the port number in hostname:portnumber format.

LDAPConnection ld = new LDAPConnection();
ld.connect("ldap1.example.com ldap2.example.com:3890
ldap3.example.com:3900", LDAPv3.DEFAULT_PORT);

Binding and Authenticating to an LDAP Server With LDAP Java SDK

When connecting to the LDAP server, your client might need to send a bind operation request to the server. This operation is also called binding to the server.

An LDAP bind request contains the following information:

  • LDAP version of the client
  • DN that is used to authenticate
  • Authentication method that is requested
  • Credentials that are used to authenticate

The client should send a bind request to the server in the following situations:

  • You want to authenticate to the server.
    For example, if you want to add or modify entries in the directory, you need to authenticate as a user with access privileges.
  • You are connecting to an LDAP v2 server.
    LDAP v2 servers typically require clients to bind before any operations can be performed.

An LDAP client can also bind as an anonymous client. For example, the LDAP server might not require authentication if your client is only searching the directory.

This section explains how to set up your client to bind to an LDAP server.

Using Simple Authentication

Simple authentication can be used when security is not a concern. If you plan to use simple authentication, use the authenticate method of the LDAPConnection object.

LDAPConnection ld = new LDAPConnection();
ld.connect("ldap.example.com", LDAPv3.DEFAULT_PORT);
ld.authenticate("uid=bjensen,ou=People,cd=example,dc=com", "hifalutin");

The server to which you bind might send back a special control to indicate that your password has expired. The server might also send back a control to indicate that your password is to expire in the near future. Refer to LDAP Controls With LDAP Java SDK for details.

Binding Anonymously

In some cases, you might not need to authenticate to the LDAP server. For example, the directory that you search might not require special access permissions for searches. Therefore, you might not need to authenticate before performing the search operation. In LDAP v3, the server no longer expects the client to send a bind request in this type of situation. In LDAP v2, the server expects the client to send a bind request, even if the operation does not require the client to authenticate.

In this kind of situation, use the authenticate method. Specify null for the DN and password.

LDAPConnection ld = new LDAPConnection();
ld.connect("ldap.example.com", LDAPv3.DEFAULT_PORT);
ld.authenticate(null, null);

Specifying the LDAP Version

As part of the bind request sent to the server, the client includes the version of the LDAP protocol that the client supports. By default, clients built with theLDAP Java SDK identify themselves as LDAP v2 clients. Therefore, explicitly identify your client as an LDAP v3 client. To identify your client as an LDAP v3 client, do one of the following:

  • Specify version 3 when invoking the authenticate method.
LDAPConnection ld = new LDAPConnection();
ld.connect("ldap.example.com", LDAPv3.DEFAULT_PORT);
ld.authenticate(3, null, null);
  • Invoke the setOption method of the LDAPConnection object to set the LDAPv3.PROTOCOL_VERSION preference to 3, then invoke the authenticate method.
LDAPConnection ld = new LDAPConnection();
ld.connect("ldap.example.com", LDAPv3.DEFAULT_PORT);
ld.setOption(LDAPv3.PROTOCOL_VERSION, 3);
ld.authenticate(null, null);

Authenticating With the connect Method

The connect method of the LDAPConnection object has a signature that allows you to authenticate and specify the LDAP version supported by your client.

You can specify all of this information using one method, rather than invoking several methods.

LDAPConnection ld = new LDAPConnection();
ld.connect(3, "ldap.example.com", LDAPv3.DEFAULT_PORT,
    "uid=bjensen,ou=People,cd=example,dc=com", "hifalutin");

Performing LDAP Operations With LDAP Java SDK

First, you initialize a session with an LDAP server. Next, you complete the authentication process. After authentication, you can perform LDAP operations.

For example, you can search the directory, add new entries, update entries that exist, and remove entries. You can perform the operations provided that the server access control allows you to request the operations.

To perform LDAP operations, invoke these methods of the LDAPConnection object:

  • To search for entries in the directory, use the search method as explained in Searching the Directory With LDAP Java SDK.
  • To retrieve a single entry in the directory, use the read method as explained in Searching the Directory With LDAP Java SDK.
  • To determine whether an attribute contains a certain value, use the compare method as explained in Comparing Attribute Values With LDAP Java SDK.
  • To add entries to the directory, use the add method as explained in Adding, Updating, and Deleting Entries With LDAP Java SDK.
  • To modify entries in the directory, use the modify method as explained in Adding, Updating, and Deleting Entries With LDAP Java SDK.
  • To delete entries from the directory, use the delete method as explained in Adding, Updating, and Deleting Entries With LDAP Java SDK.
  • To rename entries in the directory, use the rename method as explained in Adding, Updating, and Deleting Entries With LDAP Java SDK.

Closing the Connection to an LDAP Server With LDAP Java SDK

When you have finished performing all necessary LDAP operations, close the connection to the LDAP server. Use the disconnect method of the LDAPConnection object to disconnect from the LDAP server.

LDAPConnection ld = new LDAPConnection();
ld.connect("ldap.example.com", LDAPv3.DEFAULT_PORT); 
/*
 * Authenticate and perform LDAP operations.
 */
ld.disconnect();