Spring Ldap Reference PDF
Spring Ldap Reference PDF
Copyright ©
Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee
for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.
please define productname in your docbook file!
Table of Contents
Preface ..................................................................................................................................... iv
1. Introduction ............................................................................................................................ 1
1.1. Overview ..................................................................................................................... 1
1.2. Packaging overview ..................................................................................................... 4
1.3. What's new in Spring LDAP 2.0? ................................................................................. 4
1.4. Support ....................................................................................................................... 5
2. Basic Operations .................................................................................................................... 6
2.1. Search and Lookup Using AttributesMapper .................................................................. 6
2.2. Building LDAP Queries ................................................................................................ 7
2.3. Dynamically Building Distinguished Names ................................................................... 8
2.4. Binding and Unbinding ............................................................................................... 10
Binding Data ............................................................................................................ 10
Unbinding Data ........................................................................................................ 10
2.5. Modifying .................................................................................................................. 11
Modifying using rebind ........................................................................................... 11
Modifying using modifyAttributes ....................................................................... 11
2.6. Sample applications ................................................................................................... 11
3. Simpler Attribute Access and Manipulation with DirContextAdapter .......................................... 12
3.1. Introduction ............................................................................................................... 12
3.2. Search and Lookup Using ContextMapper .................................................................. 12
The AbstractContextMapper ...................................................................................... 13
3.3. Binding and Modifying Using DirContextAdapter .......................................................... 13
Binding .................................................................................................................... 13
Modifying ................................................................................................................. 14
3.4. A Complete PersonDao Class .................................................................................... 15
4. Object-Directory Mapping (ODM) .......................................................................................... 18
4.1. Introduction ............................................................................................................... 18
4.2. Annotations ............................................................................................................... 18
4.3. Type Conversion ....................................................................................................... 19
4.4. Execution .................................................................................................................. 22
5. Advanced LDAP Queries ...................................................................................................... 23
5.1. LDAP Query Builder Parameters ................................................................................ 23
5.2. Filter Criteria ............................................................................................................. 24
5.3. Hardcoded Filters ...................................................................................................... 24
6. Configuration ........................................................................................................................ 26
6.1. Introduction ............................................................................................................... 26
6.2. ContextSource Configuration ...................................................................................... 26
DirContext Authentication .......................................................................................... 28
Custom DirContext Authentication Processing .................................................... 29
Custom Principal and Credentials Management ................................................. 29
Native Java LDAP Pooling ........................................................................................ 30
Advanced ContextSource Configuration ..................................................................... 30
Custom DirContext Environment Properties ....................................................... 30
6.3. LdapTemplate Configuration ....................................................................................... 31
6.4. Obtaining a reference to the base LDAP path ............................................................. 32
7. Spring LDAP Repositories .................................................................................................... 34
7.1. Overview ................................................................................................................... 34
Preface
The Java Naming and Directory Interface (JNDI) is for LDAP programming what Java Database
Connectivity (JDBC) is for SQL programming. There are several similarities between JDBC and JNDI/
LDAP (Java LDAP). Despite being two completely different APIs with different pros and cons, they share
a number of less flattering characteristics:
• They require extensive plumbing code, even to perform the simplest of tasks.
• All resources need to be correctly closed, no matter what happens.
• Exception handling is difficult.
The above points often lead to massive code duplication in common usages of the APIs. As we all
know, code duplication is one of the worst code smells. All in all, it boils down to this: JDBC and LDAP
programming in Java are both incredibly dull and repetitive.
Spring JDBC, a part of the Spring framework, provides excellent utilities for simplifying SQL
programming. We need a similar framework for Java LDAP programming.
1. Introduction
1.1. Overview
Spring LDAP (http://www.springframework.org/ldap) is a library for simpler LDAP programming
in Java, built on the same principles as the JdbcTemplate in Spring JDBC. It completely
eliminates the need to worry about creating and closing LdapContext and looping through
NamingEnumeration. It also provides a more comprehensive unchecked Exception hierarchy, built
on Spring's DataAccessException. As a bonus, it also contains classes for dynamically building
LDAP queries and DNs (Distinguished Names), LDAP attribute management, and client-side LDAP
transaction management.
Consider, for example, a method that should search some storage for all persons and return their names
in a list. Using JDBC, we would create a connection and execute a query using a statement. We would
then loop over the result set and retrieve the column we want, adding it to a list. In contrast, using Java
LDAP, we would create a context and perform a search using a search filter. We would then loop over
the resulting naming enumeration and retrieve the attribute we want, adding it to a list.
The traditional way of implementing this person name search method in Java LDAP looks like this,
where the code marked as bold actually performs tasks related to the business purpose of the method:
package com.example.dao;
DirContext ctx;
try {
ctx = new InitialDirContext(env);
} catch (NamingException e) {
throw new RuntimeException(e);
}
while (results.hasMore()) {
SearchResult searchResult = (SearchResult) results.next();
Attributes attributes = searchResult.getAttributes();
Attribute attr = attributes.get("cn");
String cn = (String) attr.get();
list.add(cn);
}
} catch (NameNotFoundException e) {
// The base context was not found.
// Just clean up and exit.
} catch (NamingException e) {
throw new RuntimeException(e);
} finally {
if (results != null) {
try {
results.close();
} catch (Exception e) {
// Never mind this.
}
}
if (ctx != null) {
try {
ctx.close();
} catch (Exception e) {
// Never mind this.
}
}
}
return list;
}
}
By using the Spring LDAP classes AttributesMapper and LdapTemplate, we get the exact same
functionality with the following code:
package com.example.dao;
import static org.springframework.ldap.query.LdapQueryBuilder.query;
The amount of boiler-plate code is significantly less than in the traditional example. The LdapTemplate
version of the search method performs the search, maps the attributes to a string using the given
AttributesMapper, collects the strings in an internal list, and finally returns the list.
Note that the PersonDaoImpl code simply assumes that it has an LdapTemplate instance, rather
than looking one up somewhere. It provides a set method for this purpose. There is nothing Spring-
specific about this "Inversion of Control". Anyone that can create an instance of PersonDaoImpl can
also set the LdapTemplate on it. However, Spring provides a very flexible and easy way of achieving
this. The Spring container can be told to wire up an instance of LdapTemplate with its required
dependencies and inject it into the PersonDao instance. This wiring can be defined in various ways,
but the most common is through XML:
<ldap:context-source
url="ldap://localhost:389"
base="dc=example,dc=com"
username="cn=Manager"
password="secret" />
Note
In order to use the custom XML namespace for configuring the Spring LDAP components you
need to include references to this namespace in your XML declaration as in the example above.
In addition to the required dependencies the following optional dependencies are required for certain
functionality:
• spring-context (If your application is wired up using the Spring Application Context - adds the ability for
application objects to obtain resources using a consistent API. Definitely needed if you are planning
on using the BaseLdapPathBeanPostProcessor.)
• spring-tx (If you are planning to use the client side compensating transaction support)
• spring-jdbc (If you are planning to use the client side compensating transaction support)
• spring-batch (If you are planning to use the LDIF parsing functionality together with Spring Batch)
The exception is a small number of classes that have been moved to new packages in order to make a
couple of important refactorings possible. The moved classes are usually not part of the intended public
API, and the migration procedure should be very smooth - wherever a Spring LDAP class cannot be
found after upgrade, just organize the imports in your IDE.
You will probably encounter some deprecation warnings though, and there are also a lot of other API
improvements. The recommendation for getting as much as possible out of the 2.0 version is to move
away from the deprecated classes and methods and migrate to the new, improved API utilities.
• Java 1.6 is now required when using Spring LDAP. Spring versions starting at 2.0 and up are still
supported.
• The central API has been updated with Java 5 features such as generics and varargs. As
a consequence, the entire spring-ldap-tiger module has been deprecated and users are
encouraged to migrate to use the core Spring LDAP classes. The parameterization of the core
interfaces will most likely cause lots of compilation warnings, and you are obviously encouraged to
take appropriate action to get rid of these warning.
• The ODM (Object-Directory Mapping) functionality has been moved to core and there are new
methods in LdapOperations/LdapTemplate that uses this automatic translation to/from ODM-
annotated classes. See Chapter 4, Object-Directory Mapping (ODM) for more information.
• A custom XML namespace is now provided to simplify configuration of Spring LDAP. See Chapter 6,
Configuration for more information.
• Spring Data Repository and QueryDSL support is now included in Spring LDAP. See Chapter 7,
Spring LDAP Repositories for more information.
• DistinguishedName and associated classes have been deprecated in favor of standard Java
LdapName. See Section 2.3, “Dynamically Building Distinguished Names” for information on how the
library helps working with LdapNames.
• Fluent LDAP query support has been added. This makes for a more pleasant programming experience
when working with LDAP searches in Spring LDAP. See Section 2.2, “Building LDAP Queries” and
Chapter 5, Advanced LDAP Queries for more information about the LDAP query builder support.
• The old authenticate methods in LdapTemplate have been deprecated in favor of a couple
of new authenticate methods that work with LdapQuery objects and throw exceptions on
authentication failure, making it easier for the user to find out what caused an authentication attempt
to fail.
1.4. Support
Spring LDAP 2.0 is supported on Spring 2.0 and later.
2. Basic Operations
2.1. Search and Lookup Using AttributesMapper
In this example we will use an AttributesMapper to easily build a List of all common names of all
person objects.
package com.example.dao;
import static org.springframework.ldap.query.LdapQueryBuilder.query;
The inline implementation of AttributesMapper just gets the desired attribute value from the
Attributes and returns it. Internally, LdapTemplate iterates over all entries found, calling the given
AttributesMapper for each entry, and collects the results in a list. The list is then returned by the
search method.
Note that the AttributesMapper implementation could easily be modified to return a full Person
object:
package com.example.dao;
import static org.springframework.ldap.query.LdapQueryBuilder.query;
If you have the distinguished name (dn) that identifies an entry, you can retrieve the entry directly,
without searching for it. This is called a lookup in Java LDAP. The following example shows how a
lookup results in a Person object:
package com.example.dao;
This will look up the specified dn and pass the found attributes to the supplied AttributesMapper,
in this case resulting in a Person object.
Spring LDAP provides an LdapQueryBuilder with a fluent API for building LDAP Queries.
Let's say that we want to perform a search starting at the base DN dc=261consulting,dc=com,
limiting the returned attributes to "cn" and "sn", with the following filter: (&(objectclass=person)
(sn=?)), where we want the ? to be replaced with the value of the parameter lastName. This is how
we do it using the LdapQueryBuilder:
package com.example.dao;
import static org.springframework.ldap.query.LdapQueryBuilder.query;
return ldapTemplate.search(query,
new AttributesMapper() {
public Object mapFromAttributes(Attributes attrs)
throws NamingException {
return attrs.get("cn").get();
}
});
}
}
Note
In addition to simplifying building of complex search parameters, the LdapQueryBuilder and
its associated classes also provide proper escaping of any unsafe characters in search filters.
This prevents "ldap injection", where a user might use such characters to inject unwanted
operations into your LDAP operations.
Note
There are many overloaded methods in LdapTemplate for performing LDAP searches. This is
in order to accommodate for as many different use cases and programming style preferences
as possible. For the vast majority of use cases the ones that take an LdapQuery as input will
be the recommended methods to use.
Note
The AttributesMapper is just one of the available callback interfaces to use when handling
search and lookup data. See Chapter 3, Simpler Attribute Access and Manipulation with
DirContextAdapter for alternatives.
For more information on the LdapQueryBuilder see Chapter 5, Advanced LDAP Queries.
• The LdapName implementation is mutable, which is badly suited for an object representing identity.
• Despite its mutable nature, the API for dynamically building or modifying Distinguished Names using
LdapName is cumbersome. Extracting values of indexed or (particularly) named components is also
a little bit awkward.
• Many of the operations on LdapName throw checked Exceptions, requiring unnecessary try-catch
statements for situations where the error is typically fatal and cannot be repaired in a meaningful
manner.
To simplify working with Distinguished Names, Spring LDAP provides an LdapNameBuilder, as well
as a number of utility methods in LdapUtils that helps working with LdapName.
Below are a couple of examples of how these utilities can simplify handling of distinguished names.
package com.example.dao;
import org.springframework.ldap.support.LdapNameBuilder;
import javax.naming.Name;
country Sweden
The code above would then result in the following distinguished name:
package com.example.dao;
import org.springframework.ldap.support.LdapNameBuilder;
import javax.naming.Name;
public class PersonDaoImpl implements PersonDao {
...
protected Person buildPerson(Name dn, Attributes attrs) {
Person person = new Person();
person.setCountry(LdapUtils.getStringValue(dn, "c"));
person.setCompany(LdapUtils.getStringValue(dn, "ou"));
person.setFullname(LdapUtils.getStringValue(dn, "cn"));
// Populate rest of person object using attributes.
return person;
}
Since Java version <=1.4 didn't provide any public Distinguished Name implementation at all, Spring
LDAP 1.3.2 and lower provided its own implementation, DistinguishedName. This implementation
suffered from a couple of shortcomings of its own, and has been deprecated in version 2.0. Users are
now recommended to use LdapName along with the utilities described above instead.
Binding Data
Inserting data in Java LDAP is called binding. In order to do that, a distinguished name that
uniquely identifies the new entry is required. The following example shows how data is bound using
LdapTemplate:
package com.example.dao;
The Attributes building is--while dull and verbose--sufficient for many purposes. It is, however, possible
to simplify the binding operation further, which will be described in Chapter 3, Simpler Attribute Access
and Manipulation with DirContextAdapter.
Unbinding Data
Removing data in Java LDAP is called unbinding. A distinguished name (dn) is required to identify
the entry, just as in the binding operation. The following example shows how data is unbound using
LdapTemplate:
package com.example.dao;
2.5. Modifying
In Java LDAP, data can be modified in two ways: either using rebind or modifyAttributes.
A rebind is a very crude way to modify data. It's basically an unbind followed by a bind. It looks
like this:
package com.example.dao;
If only the modified attributes should be replaced, there is a method called modifyAttributes that
takes an array of modifications:
package com.example.dao;
Building Attributes and ModificationItem arrays is a lot of work, but as you will see in Chapter 3,
Simpler Attribute Access and Manipulation with DirContextAdapter, the update operations can be
simplified.
package com.example.dao;
The above code shows that it is possible to retrieve the attributes directly by name, without
having to go through the Attributes and BasicAttribute classes. This is particularly useful
when working with multi-value attributes. Extracting values from multi-value attributes normally
requires looping through a NamingEnumeration of attribute values returned from the Attributes
implementation. The DirContextAdapter can do this for you, using the getStringAttributes()
or getObjectAttributes() methods:
The AbstractContextMapper
Binding
This is an example of an improved implementation of the create DAO method. Compare it with the
previous implementation in the section called “Binding Data”.
package com.example.dao;
ldapTemplate.bind(context);
}
}
Note that we use the DirContextAdapter instance as the second parameter to bind, which should
be a Context. The third parameter is null, since we're not using any Attributes.
Also note the use of the setAttributeValues() method when setting the objectclass
attribute values. The objectclass attribute is multi-value, and similar to the troubles of extracting
muti-value attribute data, building multi-value attributes is tedious and verbose work. Using the
setAttributeValues() mehtod you can have DirContextAdapter handle that work for you.
Modifying
The code for a rebind would be pretty much identical to Example 3.4, “Binding using
DirContextAdapter”, except that the method called would be rebind. As we saw in the
section called “Modifying using modifyAttributes” a more correct approach would be to build a
ModificationItem array containing the actual modifications you want to do. This would require you
to determine the actual modifications compared to the data present in the LDAP tree. Again, this is
something that DirContextAdapter can help you with; the DirContextAdapter has the ability to
keep track of its modified attributes. The following example takes advantage of this feature:
package com.example.dao;
ldapTemplate.modifyAttributes(context);
}
}
The observant reader will see that we have duplicated code in the create and update methods. This
code maps from a domain object to a context. It can be extracted to a separate method:
package com.example.dao;
...
public void create(Person p) {
Name dn = buildDn(p);
DirContextAdapter context = new DirContextAdapter(dn);
mapToContext(p, context);
ldapTemplate.bind(context);
}
package com.example.dao;
import java.util.List;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.ldap.LdapName;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.ContextMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.filter.AndFilter;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.ldap.filter.WhitespaceWildcardsFilter;
Note
In several cases the Distinguished Name (DN) of an object is constructed using properties of the
object. E.g. in the above example, the country, company and full name of the Person are used
in the DN, which means that updating any of these properties will actually require moving the
entry in the LDAP tree using the rename() operation in addition to updating the Attribute
values. Since this is highly implementation specific this is something you'll need to keep track of
yourself - either by disallowing the user to change these properties or performing the rename()
operation in your update() method if needed.
4.2. Annotations
Entity classes managed used with the object mapping methods are required to be annotated with
annotations from the org.springframework.ldap.odm.annotations package. The available
annotations are:
• @Entry - Class level annotation indicating the objectClass definitions to which the entity maps.
(required)
• @Id - Indicates the entity DN; the field declaring this attribute must be a derivative of the
javax.naming.Name class. (required)
• @Attribute - Indicates the mapping of a directory attribute to the object class field.
• @Transient - Indicates the field is not persistent and should be ignored by the OdmManager.
The @Entry and @Id attributes are required to be declared on managed classes. @Entry is used
to specify which object classes the entity maps to. All object classes for which fields are mapped
are required to be declared. Also, in order for a directory entry to be considered a match to the
managed entity, all object classes declared by the directory entry must match be declared by in
the @Entry annotation. For example: let's assume that you have entries in your LDAP tree that
have the objectclassesinetOrgPerson,organizationalPerson,person,top. If you are only
interested in changing the attributes defined in the person objectclass, your @Entry annotation can be
The @Id annotation is used to map the distinguished name of the entry to a field. The field must be an
instance of javax.naming.Name.
The @Attribute annotation is used to map object class fields to entity fields. @Attribute is required
to declare the name of the object class property to which the field maps and may optionally declare
the syntax OID of the LDAP attribute, to guarantee exact matching. @Attribute also provides the
type declaration which allows you to indicate whether the attribute is regarded as binary based or string
based by the LDAP JNDI provider.
The @DnAttribute annotation is used to map object class fields to and from components in the
distinguished name of an entry. Fields annotated with @DnAttribute will automatically be populated
with the appropriate value from the distinguished name when an entry is read from the directory tree.
If the index attribute of all @DnAttribute annotations in a class is specified, the DN will also be
calculated when creating and updating entries. For update scenarios, this will also automatically take
care of moving entries in the tree if attributes that are part of the distinguished name have changed.
The @Transient annotation is used to indicate the field should be ignored by the object directory
mapping and not mapped to an underlying LDAP property. Note that if a @DnAttribute is not to be
bound to an Attribute, i.e. it is only part of the Distinguished Name and not represented by an object
attibute, it must also be annotated with @Transient.
1. Try to find and use a Converter registered for the fromClass, syntax and toClass and use it.
2. If this fails, then if the toClass isAssignableFrom the fromClass then just assign it.
3. If this fails try to find and use a Converter registered for the fromClass and the toClass ignoring
the syntax.
provides the logic to convert from the fromClass to the toClass. A sample configuration is provided
in the following example:
<bean id="fromStringConverter"
class="org.springframework.ldap.odm.typeconversion.impl.converters.FromStringConverter" /
>
<bean id="toStringConverter"
class="org.springframework.ldap.odm.typeconversion.impl.converters.ToStringConverter" /
>
<bean id="converterManager"
class="org.springframework.ldap.odm.typeconversion.impl.ConverterManagerFactoryBean">
<property name="converterConfig">
<set>
<bean class="org.springframework.ldap.odm.\
typeconversion.impl.ConverterManagerFactoryBean$ConverterConfig">
<property name="fromClasses">
<set>
<value>java.lang.String</value>
</set>
</property>
<property name="toClasses">
<set>
<value>java.lang.Byte</value>
<value>java.lang.Short</value>
<value>java.lang.Integer</value>
<value>java.lang.Long</value>
<value>java.lang.Float</value>
<value>java.lang.Double</value>
<value>java.lang.Boolean</value>
</set>
</property>
<property name="converter" ref="fromStringConverter" />
</bean>
<bean class="org.springframework.ldap.odm.\
typeconversion.impl.ConverterManagerFactoryBean$ConverterConfig">
<property name="fromClasses">
<set>
<value>java.lang.Byte</value>
<value>java.lang.Short</value>
<value>java.lang.Integer</value>
<value>java.lang.Long</value>
<value>java.lang.Float</value>
<value>java.lang.Double</value>
<value>java.lang.Boolean</value>
</set>
</property>
<property name="toClasses">
<set>
<value>java.lang.String</value>
</set>
</property>
<property name="converter" ref="toStringConverter" />
</bean>
</set>
</property>
</bean>
4.4. Execution
When all components have been properly configured and annotated, the object mapping methods of
LdapTemplate can be used as follows:
@Attribute(name="cn")
@DnAttribute(value="cn", index=1)
private String fullName;
@DnAttribute(value="ou", index=0)
@Transient
private String company;
@Transient
private String someUnmappedField;
// ...more attributes below
}
• base - specifies the root DN in the LDAP tree where the search should start.
• searchScope - specifies how deep into the LDAP tree the search should traverse.
• attributes - specifies the attributes to return from the search. Default is all.
• countLimit - specifies the maximum number of entries to return from the search.
• timeLimit - specifies the maximum time that the search may take.
• Search filter - the conditions that the entries we are looking for must meet.
Example 5.2 Search for all entries with objectclass person and cn=John Doe
Example 5.3 Search for all entries with objectclass person starting at dc=261consulting,dc=com
Example 5.4 Search for all entries with objectclass person starting at dc=261consulting,dc=com,
only returning the cn attribute
Example 5.5 Search for all entries with objectclass person where sn=Doe or Doo (nested query)
• like - specifies a "like" condition where wildcards can be included in the query, e.g.
where("cn").like("J*hn Doe") will result int the filter (cn=J*hn Doe).
• isPresent - specifies condition that checks for the presence of an attribute, e.g.
where("cn").isPresent() will result in the filter (cn=*).
• not - specifies that the current condition should be negated, e.g. where("sn").not().is("Doe)
will result in the filter (!(sn=Doe))
• filter(String hardcodedFilter) - uses the specified string as filter. Note that the specified
input string will not be touched in any way, meaning that this method is not particularly well suited if
you are building filters from user input.
You cannot mix the hardcoded filter methods with the where approach described above; it's either one
or the other. What this means is that if you specified a filter using filter() you will get an exception
if you try to call where afterwards.
6. Configuration
6.1. Introduction
The recommended way of configuring Spring LDAP is using the custom XML configuration namespace.
In order to make this available you need to include the Spring LDAP namespace declaration in your
bean file, e.g.:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ldap="http://www.springframework.org/schema/ldap"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://
www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/ldap http://www.springframework.org/schema/
ldap/spring-ldap.xsd">
The configurable attributes on context-source are as follows (required attributes marked with *):
Table 6.1. ContextSource Configuration Attributes
• ignore
• follow
• throw
authentication- A Id of the
strategy-ref DirContextAuthenticationStrategy
SimpleDirContextAuthenticationStrategy
instance. instance to use (see below).
DirContext Authentication
When DirContext instances are created to be used for performing operations on an LDAP server
these contexts often need to be authenticated. There are different options for configuring this using
Spring LDAP, described in this chapter.
Note
This section refers to authenticating contexts in the core functionality of the ContextSource
- to construct DirContext instances for use by LdapTemplate. LDAP is commonly used for
the sole purpose of user authentication, and the ContextSource may be used for that as well.
This process is discussed in Chapter 12, User Authentication using Spring LDAP.
Authenticated contexts are created for both read-only and read-write operations by default. You specify
username and password of the LDAP user to be used for authentication on the context-source
element.
Note
If username is the dn of an LDAP user, it needs to be the full Distinguished Name (DN) of the
user from the root of the LDAP tree, regardless of whether a base LDAP path has been specified
on the context-source element.
Some LDAP server setups allow anonymous read-only access. If you want to use anonymous Contexts
for read-only operations, set the anonymous-read-only attribute to true.
The default authentication mechanism used in Spring LDAP is SIMPLE authentication. This means that
the principal (as specified to the username attribute) and the credentials (as specified to the password)
are set in the Hashtable sent to the DirContext implementation constructor.
There are many occasions when this processing is not sufficient. For instance, LDAP Servers are
commonly set up to only accept communication on a secure TLS channel; there might be a need to use
the particular LDAP Proxy Auth mechanism, etc.
TLS
Spring LDAP provides two different configuration options for LDAP servers requiring
TLS secure channel communication: DefaultTlsDirContextAuthenticationStrategy and
ExternalTlsDirContextAuthenticationStrategy. Both these implementations will negotiate
a TLS channel on the target connection, but they differ in the actual authentication
mechanism. Whereas the DefaultTlsDirContextAuthenticationStrategy will apply SIMPLE
authentication on the secure channel (using the specified userDn and password), the
ExternalDirContextAuthenticationStrategy will use EXTERNAL SASL authentication,
applying a client certificate configured using system properties for authentication.
Since different LDAP server implementations respond differently to explicit shutdown of the TLS channel
(some servers require the connection be shutdown gracefully; others do not support it), the TLS
DirContextAuthenticationStrategy implementations support specifying the shutdown behavior
using the shutdownTlsGracefully parameter. If this property is set to false (the default), no explicit
TLS shutdown will happen; if it is true, Spring LDAP will try to shutdown the TLS channel gracefully
before closing the target context.
Note
When working with TLS connections you need to make sure that the native LDAP Pooling
functionality (as specified using the native-pooling attribute is turned off. This is particularly
important if shutdownTlsGracefully is set to false. However, since the TLS channel
negotiation process is quite expensive, great performance benefits will be gained by using the
Spring LDAP Pooling Support, described in Chapter 8, Pooling Support.
While the user name (i.e. user DN) and password used for creating an authenticated Context are
statically defined by default - the ones defined in the context-source element configuration will
be used throughout the lifetime of the ContextSource - there are several cases where this is
not the desired behaviour. A common scenario is that the principal and credentials of the current
user should be used when executing LDAP operations for that user. The default behaviour can be
modified by supplying a reference to an AuthenticationSource implementation to the context-
source element using the authentication-source-ref element, instead of explicitly specifying
the username and password. The AuthenticationSource will be queried by the ContextSource
for principal and credentials each time an authenticated Context is to be created.
If you are using Spring Security you can make sure the principal and credentials of the currently
logged in user is used at all times by configuring your ContextSource with an instance of the
SpringSecurityAuthenticationSource shipped with Spring Security.
<beans>
...
<ldap:context-source
url="ldap://localhost:389"
authentication-source-ref="springSecurityAuthenticationSource/>
<bean id="springSecurityAuthenticationSource"
class="org.springframework.security.ldap.SpringSecurityAuthenticationSource" />
...
</beans>
Note
We don't specify any username or password to our context-source when using an
AuthenticationSource - these properties are needed only when the default behaviour is
used.
Note
When using the SpringSecurityAuthenticationSource you need to use Spring Security's
LdapAuthenticationProvider to authenticate the users against LDAP.
Note
There are several serious deficiencies in the built-in LDAP connection pooling, which is why
Spring LDAP provides a more sophisticated approach to LDAP connection pooling, described
in Chapter 8, Pooling Support. If pooling functionality is required, this is the recommended
approach.
Note
Regardless of the pooling configuration, the ContextSource#getContext(String
principal, String credentials) method will always explicitly not use native Java LDAP
Pooling, in order for reset passwords to take effect as soon as possible.
In some cases the user might want to specify additional environment setup properties in addition to the
ones directly configurable on context-source. Such properties should be set in a Map and referenced
in the base-env-props-ref attribute.
<ldap:ldap-template />
This will create an LdapTemplate instance with the default id, referencing the default
ContextSource, which is expected to have the id contextSource (the default for the context-
source element).
• OBJECT
• ONELEVEL
• SUBTREE
For that reason, Spring LDAP has a mechanism by which any Spring controlled bean may be supplied
the base path on startup. For beans to be notified of the base path, two things need to be in place:
First of all, the bean that wants the base path reference needs to implement the BaseLdapNameAware
interface. Secondly, a BaseLdapPathBeanPostProcessor needs to be defined in the application
context
package com.example.service;
public class PersonService implements PersonService, BaseLdapNameAware {
...
private LdapName basePath;
<beans>
...
<ldap:context-source
username="cn=Administrator"
password="secret"
url="ldap://localhost:389"
base="dc=261consulting,dc=com" />
...
<bean class="org.springframework.ldap.core.support.BaseLdapPathBeanPostProcessor" />
</beans>
The default behaviour of the BaseLdapPathBeanPostProcessor is to use the base path of the
single defined BaseLdapPathSource (AbstractContextSource)in the ApplicationContext. If
more than one BaseLdapPathSource is defined, you will need to specify which one to use with the
baseLdapPathSourceName property.
• Spring LDAP repositories can be enabled using an <ldap:repositories> tag in your XML
configuration or using an @EnableLdapRepositories annotation on a configuration class.
• To include support for LdapQuery parameters in automatically generated repositories, have your
interface extend LdapRepository rather than CrudRepository.
• All Spring LDAP repositories must work with entities annotated with the ODM annotations, as
described in Chapter 4, Object-Directory Mapping (ODM).
• Since all ODM managed classes must have a Distinguished Name as ID, all Spring LDAP
repositories must have the ID type parameter set to javax.naming.Name. Indeed, the built-in
SpringLdapRepository only takes one type parameter; the managed entity class, defaulting ID
to javax.naming.Name.
• Due to specifics of the LDAP protocol, paging and sorting is not supported for Spring LDAP
repositories.
8. Pooling Support
8.1. Introduction
Pooling LDAP connections helps mitigate the overhead of creating a new LDAP connection for each
LDAP interaction. While Java LDAP pooling support exists it is limited in its configuration options
and features, such as connection validation and pool maintenance. Spring LDAP provides support for
detailed pool configuration on a per- ContextSource basis.
Note
Connections will be automatically invalidated if they throw an exception
that is considered non-transient. E.g. if a DirContext instance throws a
javax.naming.CommunicationException, this will be interpreted as a non-transient error
and the instance will be automatically invalidated, without the overhead of an additional
testOnReturn operation. The exceptions that are interpreted as non-transient are configured
using the nonTransientExceptions property of the PoolingContextSource.
8.4. Configuration
Configuring pooling should look very familiar if you're used to Jakarta Commons-Pool or Commons-
DBCP. You will first create a normal ContextSource then wrap it in a PoolingContextSource .
<beans>
...
<ldap:context-source
password="secret" url="ldap://localhost:389" username="cn=Manager">
<ldap:pooling />
</ldap:context-source>
...
</beans>
In a real world example you would probably configure the pool options and enable connection validation;
the above serves as an example to demonstrate the general idea.
Validation Configuration
Adding validation and a few pool configuration tweaks to the above example is straight forward. Inject
a DirContextValidator and set when validation should occur and the pool is ready to go.
<beans>
...
<ldap:context-source
username="cn=Manager" password="secret" url="ldap://localhost:389" >
<ldap:pooling
test-on-borrow="true"
test-while-idle="true" />
</ldap:context-source>
...
</beans>
The above example will test each DirContext before it is passed to the client application and test
DirContexts that have been sitting idle in the pool.
Let's say that you want to call the following DirContext method:
There is no corresponding overloaded method in LdapTemplate. The way to solve this is to use a custom
SearchExecutor implementation:
In your custom executor, you have access to a DirContext object, which you use to call
the method you want. You then provide a handler that is responsible for mapping attributes
and collecting the results. You can for example use one of the available implementations of
CollectingNameClassPairCallbackHandler, which will collect the mapped results in an internal
list. In order to actually execute the search, you call the search method in LdapTemplate that takes an
executor and a handler as arguments. Finally, you return whatever your handler has collected.
package com.example.dao;
CollectingNameClassPairCallbackHandler handler =
new AttributesMapperCallbackHandler(new PersonAttributesMapper());
ldapTemplate.search(executor, handler);
return handler.getList();
}
}
If you prefer the ContextMapper to the AttributesMapper, this is what it would look like:
package com.example.dao;
CollectingNameClassPairCallbackHandler handler =
new ContextMapperCallbackHandler(new PersonContextMapper());
ldapTemplate.search(executor, handler);
return handler.getList();
}
}
Note
When using the ContextMapperCallbackHandler you must make sure that you have called
setReturningObjFlag(true) on your SearchControls instance.
When implementing a custom ContextExecutor, you can choose between using the
executeReadOnly() or the executeReadWrite() method. Let's say that we want to call this
method:
It's available in DirContext, but there is no matching method in LdapTemplate. It's a lookup method,
so it should be read-only. We can implement it like this:
package com.example.dao;
return ldapTemplate.executeReadOnly(executor);
}
}
In the same manner you can execute a read-write operation using the executeReadWrite() method.
Example 9.3 A custom DirContext method using ContextExecutor
Before the search operation, the preProcess method is called on the given DirContextProcessor
instance. After the search has been executed and the resulting NamingEnumeration has been
processed, the postProcess method is called. This enables a user to perform operations on the
DirContext to be used in the search, and to check the DirContext when the search has been
performed. This can be very useful for example when handling request and response controls.
There are also a few convenience methods for those that don't need a custom SearchExecutor:
createRequestControl, and of course the postProcess method for performing whatever you need
to do after the search.
package com.example.control;
Note
Make sure you use LdapContextSource when you use Controls. The Control interface is
specific for LDAPv3 and requires that LdapContext is used instead of DirContext. If an
AbstractRequestControlDirContextProcessor subclass is called with an argument that
is not an LdapContext, it will throw an IllegalArgumentException.
manually limit the search result into pages, or retrieve the whole result and then chop it into pages of
suitable size. The former would be rather complicated, and the latter would be consuming unnecessary
amounts of memory.
Some LDAP servers have support for the PagedResultsControl, which requests that the results of
a search operation are returned by the LDAP server in pages of a specified size. The user controls the
rate at which the pages are returned, simply by the rate at which the searches are called. However, the
user must keep track of a cookie between the calls. The server uses this cookie to keep track of where
it left off the previous time it was called with a paged results request.
Spring LDAP provides support for paged results by leveraging the concept for pre- and postprocessing
of an LdapContext that was discussed in the previous sections. It does so using the
class PagedResultsDirContextProcessor. The PagedResultsDirContextProcessor class
creates a PagedResultsControl with the requested page size and adds it to the LdapContext.
After the search, it gets the PagedResultsResponseControl and retrieves the paged results cookie,
which is needed to keep the context between consecutive paged results requests.
Below is an example of how the paged search results functionality may be used:
do {
List<String> oneResult = operations.search(
"ou=People",
"(&(objectclass=person))",
searchControls,
CN_ATTRIBUTES_MAPPER,
processor);
result.addAll(oneResult);
} while(processor.hasMore());
return result;
}
});
}
Note
In order for a paged results cookie to continue being valid, it is imperative that the same
underlying connection is used for each paged results call. This can be accomplished using the
SingleContextSource, as demonstrated in the example.
In addition to the actual transaction management, Spring LDAP transaction support also makes sure that
the same DirContext instance will be used throughout the same transaction, i.e. the DirContext
will not actually be closed until the transaction is finished, allowing for more efficient resources usage.
Note
It is important to note that while the approach used by Spring LDAP to provide transaction support
is sufficient for many cases it is by no means "real" transactions in the traditional sense. The
server is completely unaware of the transactions, so e.g. if the connection is broken there will
be no hope to rollback the transaction. While this should be carefully considered it should also
be noted that the alternative will be to operate without any transaction support whatsoever; this
is pretty much as good as it gets.
Note
The client side transaction support will add some overhead in addition to the work required by the
original operations. While this overhead should not be something to worry about in most cases,
if your application will not perform several LDAP operations within the same transaction (e.g. a
modifyAttributes followed by a rebind), or if transaction synchronization with a JDBC data
source is not required (see below) there will be nothing to gain by using the LDAP transaction
support.
11.2. Configuration
Configuring Spring LDAP transactions should look very familiar if you're used to configuring
Spring transactions. You will annotate your transacted classes with @Transactional, create a
TransactionManager instance and include a <tx:annotation-driven> tag in your bean
configuraion.
<beans>
...
<ldap:context-source
url="ldap://localhost:389"
base="dc=example,dc=com"
username="cn=Manager"
password="secret" />
<!--
The MyDataAccessObject class is annotated with @Transactional.
-->
<bean id="myDataAccessObject" class="com.example.MyDataAccessObject">
<property name="ldapTemplate" ref="ldapTemplate" />
</bean>
<tx:annotation-driven />
...
Note
While this setup will work fine for most simple use cases, some more complex scenarios will
require additional configuration; more specifically if you will be creating or deleting subtrees within
transactions, you will need to use an alternative TempEntryRenamingStrategy, as described
in the section called “Renaming Strategies” below
In a real world example you would probably apply the transactions on the service object level rather
than the DAO level; the above serves as an example to demonstrate the general idea.
Note
Once again it should be noted that the provided support is all client side. The wrapped transaction
is not an XA transaction. No two-phase as such commit is performed, as the LDAP server will
be unable to vote on its outcome. Once again, however, for the majority of cases the supplied
support will be sufficient.
The same thing can be accomplished for Hibernate integration by supplying a session-factory-
ref attribute to the <ldap:transaction-manager> tag.
This enables the system to perform compensating operations should the transaction need to be rolled
back. In many cases the compensating operation is pretty straightforward. E.g. the compensating
rollback operation for a bind operation will quite obviously be to unbind the entry. Other operations
however require a different, more complicated approach because of some particular characteristics of
LDAP databases. Specifically, it is not always possible to get the values of all Attributes of an entry,
making the above strategy insufficient for e.g. an unbind operation.
This is why each modifying operation performed within a Spring LDAP managed transaction is internally
split up in four distinct operations - a recording operation, a preparation operation, a commit operation,
and a rollback operation. The specifics for each LDAP operation is described in the table below:
Table 11.1.
unbind Make record of Rename the entry Unbind the Rename the
the original DN to the temporary temporary entry. entry from the
and calculate a location. temporary
temporary DN.
rebind Make record Rename the entry Bind the new Rename the
of the original to a temporary Attributes at entry from the
DN and the new location. the original DN, temporary
Attributes, and unbind the location back to
and calculate a original entry from its original DN.
temporary DN. its temporary
location.
Make record of
modifyAttributes Perform the No operation. Perform a
the DN of the modifyAttributes modifyAttributes
entry to modify operation. operation using
and calculate the calculated
compensating compensating
ModificationItems ModificationItems.
for the
modifications to
be done.
A more detailed description of the internal workings of the Spring LDAP transaction support is available
in the javadocs.
Renaming Strategies
As described in the table above, the transaction management of some operations require the original
entry affected by the operation to be temporarily renamed before the actual modification can be made
in the commit. The manner in which the temporary DN of the entry is calculated is managed by a
TempEntryRenamingStrategy specified in a sub-element to the <ldap:transaction-manager
> declaration in the configuration. Two implementations are supplied with Spring LDAP:
Note
There are some situations where the DefaultTempEntryRenamingStrategy will
not work. E.g. if your are planning to do recursive deletes you'll need to use
DifferentSubtreeTempEntryRenamingStrategy. This is because the recursive delete
operation actually consists of a depth-first delete of each node in the sub tree
individually. Since it is not allowed to rename an entry that has any children, and
DefaultTempEntryRenamingStrategy would leave each node in the same subtree (with a
different name) in stead of actually removing it, this operation would fail. When in doubt, use
DifferentSubtreeTempEntryRenamingStrategy.
The userDn supplied to the authenticate method needs to be the full DN of the user to authenticate
(regardless of the base setting on the ContextSource). You will typically need to perform an LDAP
search based on e.g. the user name to get this DN:
if(result.size() != 1) {
throw new RuntimeException("User not found or not unique");
}
return (String)result.get(0);
}
There are some drawbacks to this approach. The user is forced to concern herself with the DN of
the user, she can only search for the user's uid, and the search always starts at the root of the tree
(the empty path). A more flexible method would let the user specify the search base, the search filter,
and the credentials. Spring LDAP includes an authenticate method in LdapTemplate that provide this
functionality: boolean authenticate(LdapQuery query, String password);
ldapTemplate.authenticate(query().where("uid").is("john.doe"), "secret");
Note
As described in below, some setups may require additional operations to be performed in order
for actual authentication to occur. See Section 12.2, “Performing Operations on the Authenticated
Context” for details.
Tip
Don't write your own custom authenticate methods. Use the ones provided in Spring LDAP 1.3.x.
Example 12.2 Performing an LDAP operation on the authenticated context using Spring LDAP.
The org.springframework.ldap.ldif package provides classes needed to parse LDIF files and deserialize
them into tangible objects. The LdifParser is the main class of the org.springframework.ldap.ldif package
and is capable of parsing files that are RFC 2849 compliant. This class reads lines from a resource
and assembles them into an LdapAttributes object. The LdifParser currently ignores changetype LDIF
entries as their usefulness in the context of an application has yet to be determined.
LdapAttribute objects represent options as a Set<String>. The DN support added to the LdapAttributes
object employs the javax.naming.ldap.LdapName class.
• SeparatorPolicy - establishes the mechanism by which lines are assembled into attributes.
• Specification - provides a mechanism by which object structure can be validated after assembly.
The SeparatorPolicy determines how individual lines read from the source file should be interpreted
as the LDIF specification allows attributes to span multiple lines. The default policy assess lines in the
context of the order in which they were read to determine the nature of the line in consideration. control
attributes and changetype records are ignored.
There are 5 classes in this package which offer three basic use cases:
• Use Case 1: Read LDIF records from a file and return an LdapAttributes object.
• Use Case 2: Read LDIF records from a file and map records to Java objects (POJOs).
The first use case is accomplished with the LdifReader. This class
extends Spring Batch's AbstractItemCountingItemSteamItemReader and implements its
ResourceAwareItemReaderItemStream. It fits naturally into the framework and can be used to read
LdapAttributes objects from a file.
The MappingLdifReader can be used to map LDIF objects directly to any POJO. This class requires an
implementation of the RecordMapper interface be provided. This implementation should implement the
logic for mapping objects to POJOs.
The RecordCallbackHandler can be implemented and provided to either reader. This handler can be
used to operate on skipped records. Consult the Spring Batch documentation for more information.
The last member of this package, the LdifAggregator, can be used to write LDIF records to a file. This
class simply invokes the toString() method of the LdapAttributes object.
14. Utilities
14.1. Incremental Retrieval of Multi-Valued Attributes
When there are a very large number of attribute values (>1500) for a specific attribute, Active Directory
will typically refuse to return all these values at once. Instead the attribute values will be returned
according to the Incremental Retrieval of Multi-valued Properties method. This requires the calling part
to inspect the returned attribute for specific markers and, if necessary, make additional lookup requests
until all values are found.
Spring LDAP's
org.springframework.ldap.core.support.DefaultIncrementalAttributesMapper
helps working with this kind of attributes, as follows:
This will parse any returned attribute range markers and make repeated requests as necessary until all
values for all requested attributes have been retrieved.
Note
As of Spring LDAP 2.0 the core API has full Java 5 support, and SimpleLdapTemplate and
associated classes are all deprecated.
As of version 1.3 Spring LDAP includes the spring-ldap-core-tiger.jar distributable, which adds a thin
layer of Java 5 functionality on top of Spring LDAP.
The SimpleLdapTemplate class adds search and lookup methods that take a
ParameterizedContextMapper, adding generics support to these methods.
return person;
}
};
}