Chapter 10. User Authentication using Spring LDAP

Table of Contents

Basic Authentication
Performing Operations on the Authenticated Context
Retrieving the Authentication Exception
Use Spring Security

Basic Authentication

While the core functionality of the ContextSource is to provide DirContext instances for use by LdapTemplate, it may also be used for authenticating users against an LDAP server. The getContext(principal, credentials) method of ContextSource will do exactly that; construct a DirContext instance according to the ContextSource configuration, authenticating the context using the supplied principal and credentials. A custom authenticate method could look like this:

public boolean authenticate(String userDn, String credentials) {
  DirContext ctx = null;
  try {
    ctx = contextSource.getContext(userDn, credentials);
    return true;
  } catch (Exception e) {
    // Context creation failed - authentication did not succeed
    logger.error("Login failed", e);
    return false;
  } finally {
    // It is imperative that the created DirContext instance is always closed
    LdapUtils.closeContext(ctx);
  }
}

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:

private String getDnForUser(String uid) {
  Filter f = new EqualsFilter("uid", uid);
  List result = ldapTemplate.search(DistinguishedName.EMPTY_PATH, f.toString(),
      new AbstractContextMapper() {
    protected Object doMapFromContext(DirContextOperations ctx) {
      return ctx.getNameInNamespace();
    }
  });
  
  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 1.3.0 introduced new authenticate methods in LdapTemplate that provide this functionality:

  • boolean authenticate(Name base, String filter, String password);

  • boolean authenticate(String base, String filter, String password);

Using one of these methods, authentication becomes as simple as this:

Example 10.1. Authenticating a user using Spring LDAP.

boolean authenticated = ldapTemplate.authenticate("", "(uid=john.doe)", "secret");


Tip

Don't write your own custom authenticate methods. Use the ones provided in Spring LDAP 1.3.x.