Using DirContextSource

This user guide is comprised of two examples of the DirContextSource and also several notes on authentication.

TIP
If you are using Actve Directory then this component is best combined with my Active Directory JNDI/LDAP DNS Provider Implementation.

Contents:

Basic Example

In few lines you have a usable DirContextSource:

import net.sf.michaelo.dirctxsrc.DirContextSource;
import javax.naming.directory.DirContext;
[…]
DirContextSource.Builder builder = new DirContextSource.Builder("ldap://hostname");
DirContextSource contextSource = builder.build();
// try and catch block omitted for the sake of brevity,
// handle NamingException appropriately
DirContext context = contextSource.getDirContext();
// Perform operations
context.close();
[…]

Advanced Example

A more complex example includes several configuration options as described in the builder's Javadoc:

import net.sf.michaelo.dirctxsrc.DirContextSource;
import javax.naming.directory.DirContext;
[…]
// Use several hostnames in the case if one fails
DirContextSource.Builder builder = new DirContextSource.Builder("ldap://hostname",
                                 "ldap://hostname2", "ldap://distant-hostname");
// I'd like to see all comm on System.err
builder.debug();
// Hosts are unreliable, so keep trying
builder.retries(5).retryWait(5000);

DirContextSource contextSource = builder.build();
// try and catch block omitted for the sake of brevity,
// handle NamingException appropriately
DirContext context = contextSource.getDirContext();
// Perform operations
context.close();
[…]

Authentication

The DirContextSource supports two types of authentication mechanisms, none/anonymous and GSS-API with Kerberos 5.

Note
Other mechanisms are not directly supported because I never needed them. If you need any, please file an issue.
  • Anonymous auth: works out of the box, the builder is configured for this mechanism by default.
  • GSS-API (Kerberos 5) auth: requires a bit more work. Make sure that JVM is properly configured for Kerberos and add the following to the basic example builder:
    […]
    builder.gssApiAuth();
    […]
    

    The above example presumes that you have configured your JAAS login file with the default login entry name DirContextSource. If you prefer an alternative name configure as follows:

    […]
    builder.gssApiAuth("MyAlternativeEntryName");
    […]
    

    There are a few more options for this authentication mechanism, like mutual auth or auth integrity and/or privacy protection. See the builder's Javadoc for more details.