Ldap Utilities

Notice

The latest version of this library has moved to google code.
Please migrate to the latest version and update your links.



Author Daniel Fisher
License LGPL/Apache2
Latest Version 2.8.4
Download
API Documentation

Description

These ldap utilities were created to do common tasks, such as authentication, queries, and updates.
The Ldap class itself can be used as a Java Bean.
Support for SASL EXTERNAL, GSS-API, DIGEST-MD5, and CRAM-MD5.
Support for connection pooling is available using the LdapPool class.
Support for creating DSML version 1 and 2.
Support for creating LDIFs.

Sample Code

Ldap Class

import edu.vt.middleware.ldap.Ldap;
import edu.vt.middleware.ldap.LdapConfig;
import edu.vt.middleware.ldap.ldif.util.Ldif;
 
String query = "search_query";
Ldap ldap = new Ldap(new LdapConfig(your_host, your_base));
(new Ldif()).outputLdif(ldap.search(query, null), System.out);

Authenticator Class

import edu.vt.middleware.ldap.Authenticator;
import edu.vt.middleware.ldap.LdapConfig;
 
String user = "valid_user";
String credential = "valid_password";
Authenticator auth = new Authenticator(new LdapConfig(your_host, your_base));
auth.useTls(true);
if (auth.authenticate(user, credential)) {
  // user authenticated
} else {
  // authentication failed
}

LdapPool Class

import edu.vt.middleware.ldap.Ldap;
import edu.vt.middleware.ldap.LdapConfig;
import edu.vt.middleware.ldap.LdapPool;
 
int maxSleeping = 8;
int initSize = 4;
LdapConfig ldapConfig = new LdapConfig(your_host, your_base);
LdapPool pool = new LdapPool(ldapConfig, maxSleeping, initSize);
Ldap ldap = null;
try {
  ldap = (Ldap) pool.borrowObject();
  // do something with the ldap object
} finally {
  if (ldap != null) {
    try {
      pool.returnObject(ldap);
    } catch (Exception e) {}
  }
}

Dsml Class

import edu.vt.middleware.ldap.LdapAttribute;
import edu.vt.middleware.ldap.LdapEntry;
import edu.vt.middleware.ldap.dsml.DsmlResult;
 
DsmlResult result = new DsmlResult();
LdapEntry entry = new LdapEntry("uupid=dfisher,ou=People,dc=vt,dc=edu");
LdapAttribute gn = new LdapAttribute("givenName", "Daniel");
entry.addAttribute(gn);
LdapAttribute sn = new LdapAttribute("sn", "Fisher");
entry.addAttribute(sn);
result.addEntry(entry);
String dsml = result.toDsmlv1();

Ldif Class

import edu.vt.middleware.ldap.LdapAttribute;
import edu.vt.middleware.ldap.LdapEntry;
import edu.vt.middleware.ldap.ldif.LdifResult;
 
LdifResult result = new LdifResult();
LdapEntry entry = new LdapEntry("uupid=dfisher,ou=People,dc=vt,dc=edu");
LdapAttribute gn = new LdapAttribute("givenName", "Daniel");
entry.addAttribute(gn);
LdapAttribute sn = new LdapAttribute("sn", "Fisher");
entry.addAttribute(sn);
result.addEntry(entry);
String ldif = result.toLdif();

Properties Support

The Ldap and Authenticator objects can now be configured with a properties file.
Simply edit the ldap.properties file and place it in your classpath.
When you construct your Ldap object instead of using the LdapConfig class, do this:

import edu.vt.middleware.ldap.Ldap
 
Ldap ldap = new Ldap();
ldap.loadFromProperties();

Your ldap object will be configured with the settings you supply.

Ldap Properties

Property Name Default Value Description
edu.vt.middleware.ldap.contextFactory com.sun.jndi.ldap.LdapCtxFactory fully qualified class name of the context factory that JNDI should use
edu.vt.middleware.ldap.sslSocketFactory none fully qualified class name which implements javax.net.ssl.SSLSocketFactory
edu.vt.middleware.ldap.hostnameVerifier none fully qualified class name which implements javax.net.ssl.HostnameVerifier
edu.vt.middleware.ldap.host none hostname of the LDAP
edu.vt.middleware.ldap.port 389 port the LDAP is listening on
edu.vt.middleware.ldap.base none base dn for performing searches
edu.vt.middleware.ldap.serviceUser none dn to bind as before searching
edu.vt.middleware.ldap.serviceCredential none credential for the service user
edu.vt.middleware.ldap.authtype simple LDAP authentication mechanism
edu.vt.middleware.ldap.authoritative false require an authoritative source
edu.vt.middleware.ldap.timeLimit 0 the amount of time in milliseconds that search operations will block
edu.vt.middleware.ldap.countLimit 0 the maximum number of entries that search operations will return
edu.vt.middleware.ldap.batchSize -1 the batch size to use when returning results
edu.vt.middleware.ldap.dnsUrl none the DNS url to use for hostname resolution
edu.vt.middleware.ldap.language none the preferred language
edu.vt.middleware.ldap.referral none specifies how referrals should be handled, must be one of 'throw', 'ignore', or 'follow'
edu.vt.middleware.ldap.derefAliases none specifies how aliases should be handled, must be one of 'always', 'never', 'finding', or 'searching'
edu.vt.middleware.ldap.binaryAttributes none specifies additional attributes which should be treated as binary
edu.vt.middleware.ldap.typesOnly false only return attribute type names
edu.vt.middleware.ldap.removeUrls true whether URLs should be removed from non-relative names
edu.vt.middleware.ldap.ssl false whether SSL should be used for LDAP connections
edu.vt.middleware.ldap.tls false whether TLS should be used for LDAP connections

Authenticator Properties

All Ldap properties are inherited and can be overridden as necessary.

Property Name Default Value Description
edu.vt.middleware.ldap.auth.userField uid LDAP field which contains user identifier to search on, supports a comma delimited list for multiple values
edu.vt.middleware.ldap.auth.constructDn false whether the authentication dn should be constructed or looked up in the LDAP
edu.vt.middleware.ldap.auth.subtreeSearch false whether the authentication dn should be searched for over the entire base
edu.vt.middleware.ldap.auth.logCredentials false whether authentication credentials should be logged, logging occurs at debug level
edu.vt.middleware.ldap.auth.authorizationFilter none ldap filter to use for performing authorization after successful authentication

Servlet Support

This package now includes a Login and Logout servlet for use with web applications.
This provides a drop in solution for those wishing to do simple authentication and authorization via Ldap.

Configuration

To configure these servlets, add the following to your web.xml file:

    <!-- Servlet which can be used to perform ldap authentication --> 
    <servlet>
      <servlet-name>Login</servlet-name>
      <servlet-class>edu.vt.middleware.ldap.servlets.LoginServlet</servlet-class>
      <!-- properties file to configure Authenticator with
           default is '/ldap.properties' --> 
      <init-param>
        <param-name>edu.vt.middleware.ldap.servlets.propertiesFile</param-name>
        <param-value>/my.ldap.properties</param-value>
      </init-param>
      <!-- session attribute to set which will contain the user identifier
           default is 'user' --> 
      <init-param>
        <param-name>edu.vt.middleware.ldap.servlets.sessionId</param-name>
        <param-value>application.user</param-value>
      </init-param>
      <!-- URL of the page that collects user credentials
           default is '/' --> 
      <init-param>
        <param-name>edu.vt.middleware.ldap.servlets.loginUrl</param-name>
        <param-value>login.jsp</param-value>
      </init-param>
      <!-- Error message to display if authentication fails
           default is 'Could not authenticate or authorize user' --> 
      <init-param>
        <param-name>edu.vt.middleware.ldap.servlets.errorMsg</param-name>
        <param-value>Invalid credentials</param-value>
      </init-param>
      <!-- Class which extends
           edu.vt.middleware.ldap.servlets.session.SessionManager
           This param is optional, and only needed if additional
           session initialization is required
           By default the only session initialization that occurs is
           to set the sessionId to the user name --> 
      <init-param>
        <param-name>edu.vt.middleware.ldap.servlets.sessionManager</param-name>
        <param-value>path.to.your.package.customSessionManager</param-value>
      </init-param>
    </servlet>
    <servlet-mapping>
      <servlet-name>Login</servlet-name>
      <url-pattern>/Login</url-pattern>
    </servlet-mapping>
 
    <!-- Servlet used to remove the session attribute set by Login --> 
    <servlet>
      <servlet-name>Logout</servlet-name>
      <servlet-class>edu.vt.middleware.ldap.servlets.LogoutServlet</servlet-class>
      <!-- session attribute to remove which contains the user identifier
           if set it must match the sessionId param set in the Login servlet
           default is 'user' -->
      <init-param>
        <param-name>edu.vt.middleware.ldap.servlets.sessionId</param-name>
        <param-value>application.user</param-value>
      </init-param>
      <!-- Class which extends
           edu.vt.middleware.ldap.servlets.session.SessionManager
           This param is optional, and only needed if additional
           session cleanup is required
           By default the only session cleanup that occurs is
           to remove the sessionId -->
      <init-param>
        <param-name>edu.vt.middleware.ldap.servlets.sessionManager</param-name>
        <param-value>path.to.your.package.customSessionManager</param-value>
      </init-param>
    </servlet>
    <servlet-mapping>
      <servlet-name>Logout</servlet-name>
      <url-pattern>/Logout</url-pattern>
    </servlet-mapping>

Here is some sample HTML for using the login servlet:

    <form method="post" action="Login">
      <input type="text" name="user"/>
      <input type="password" name="credential"/>
      <input type="hidden" name="url" value="url to redirect to after login"/>
      <input type="submit" name="login" value="Login"/>
    </form>

JAAS Support

A LoginModule is provided and can be configured with the following JAAS file:

vt-ldap {
   edu.vt.middleware.ldap.jaas.LdapLoginModule required
     host="authn.directory.vt.edu"
     base="ou=people,dc=vt,dc=edu"
     tls="true"
     userField="uupid"
     roleBase="ou=groups,dc=vt,dc=edu"
     roleFilter="(member={0})"
     roleAttribute="uugid"
     userRoleAttribute="eduPersonAffiliation";
};

To use a JAAS configuration file you must set the following java property to the location of the file: java.security.auth.login.config
The LdapLoginModule contains a main method and can be called from the command-line.

JAAS Parameters

Each option corresponds to an Ldap Property without the domain prefix.
In addition each role option can be used to override any existing option.
For example, if you want to get your role data from a different host, simply set roleHost=“my.host.domain”.
There are 3 parameters which do not correspond to Ldap properties and those are explained below:

roleFilterAn LDAP search filter where {0} is replaced with the user dn and {1} is replaced with the user. This is used to find roles for the user.
roleAttributeAn attribute(s) that exists on any role entries found with the roleFilter. The value(s) of these attributes will be added as roles for this user. Comma delimited for multiple attributes.
userRoleAttributeAn attribute(s) that exists on the user entry. The value(s) of these attributes will be added as roles for this user. Comma delimited for multiple attributes.

Tomcat Realm Support

The JAAS module can be used as a Tomcat realm.
Here are the instructions to do so:

  1. Put the vt-ldap jar in the Tomcat server classpath
  2. Set the java.security.auth.login.config property to the location of your JAAS file
    • can be done by setting a shell environment variable or editing the bin/catalina.sh script
  3. Add the realm declaration to the Tomcat server.xml file:
    <Realm className="org.apache.catalina.realm.JAASRealm"
           appName="vt-ldap"
           userClassNames="edu.vt.middleware.ldap.jaas.LdapPrincipal"
           roleClassNames="edu.vt.middleware.ldap.jaas.LdapRole"/>

    note that appName must be the same as the declaration in your JAAS file.

  4. Configure your web.xml to use your LDAP roles:
      <security-constraint>
        <web-resource-collection>
          <web-resource-name>My webapp</web-resource-name>
          <url-pattern>/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
           <role-name>staff</role-name>
        </auth-constraint>
      </security-constraint>
  5. Restart tomcat
 
middleware/opensource/ldap.txt · Last modified: 2009/10/07 17:17 (external edit)
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki