Integrating with LDAP

Showing 1-7 of 7 messages
Integrating with LDAP hyder 3/13/10 12:14 AM

If I want to use users from an LDAP source, how to do that?

Also, when deploying in production, I would like to use my container's
LDAP integration capabilities. Is this possible?

Thanks a lot!

Re: Integrating with LDAP grandfatha 3/13/10 10:46 AM
You can use the JNDI APIs to establish a connection to your LDAP
server and do a bind/search for the attributes/nodes/etc that you
would like retrieve from LDAP.

A nicer to code solution would be to use "Spring LDAP", a subproject
of the Spring Framework, which eliminates most of the ugly, repetitive
JNDI code and gives you nice callbacks. Think of it like Spring JDBC
is on top of regular JDBC.

A sample snippet with Spring LDAP is the following:

public class LDAPContactDAO implements ContactDAO{
    private LdapTemplate ldapTemplate;
    public void setLdapTemplate(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;

    public List getAllContactNames() {
        return"", "(objectclass=person)",
                new AttributesMapper() {
                    public Object mapFromAttributes(Attributes attrs)
                            throws NamingException {
                        return attrs.get("cn").get();


(taken from here:

which is the shorter version to what you would need to write with JNDI
like the following:

public class SimpleLDAPClient {
    public static void main(String[] args) {
        Hashtable env = new Hashtable();

        env.put(Context.PROVIDER_URL, "ldap://localhost:10389/
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
        env.put(Context.SECURITY_CREDENTIALS, "secret");
        DirContext ctx = null;
        NamingEnumeration results = null;
        try {
            ctx = new InitialDirContext(env);
            SearchControls controls = new SearchControls();
            results ="", "(objectclass=person)",
            while (results.hasMore()) {
                SearchResult searchResult = (SearchResult);
                Attributes attributes = searchResult.getAttributes();
                Attribute attr = attributes.get("cn");
                String cn = (String) attr.get();
                System.out.println(" Person Common Name = " + cn);
        } catch (NamingException e) {
            throw new RuntimeException(e);
        } finally {
            if (results != null) {
                try {
                } catch (Exception e) {
            if (ctx != null) {
                try {
                } catch (Exception e) {

Here is a sample by the creators of Spring LDAP on how to do
authentication using Spring LDAP:

Re: Integrating with LDAP hyder 3/31/10 2:16 AM

So, this is what I tried:

1) Started with the yabe sample, verified that everything is working.
Also, installed Apache Directory and Studio.
2) Added the spring module support and my application-context.xml.
3) Copied spring ldap jars into the spring module lib directory.
4) Wrote a Person model class and a utility class (copied from the
Spring LDAP sample (
) with a couple of
5) Then, I tried to change the authenticate method in the Security
class and the setConnectedUser method in Admin.

Here, I get a bit confused and also ran into a couple of problems:

User user = User.find("byEmail", Security.connected()).first();

How do I change this so that I can use spring ldap instead? The
"byEmail" operates on JPA whereas I need to find on LDAP. I notice
that it's not taking any parameter so how can I make my LDAP search?

2nd, I also get this error:
The file /app/controllers/ could not be compiled. Error
raised is : Secure.Security cannot be resolved to a type.

In the console, I can see this:
play.exceptions.JavaCompilationException: Secure.Security cannot be
resolved to a type
        at play.classloading.ApplicationCompiler
        at org.eclipse.jdt.internal.compiler.Compiler.compile(
        at {module:crud}/app/views/tags/crud/types.tag.(line:3)
        at play.templates.Template.render(
        at play.templates.Template$ExecutableTemplate.invokeTag(
        at {module:crud}/conf/routes.(line:4)
        at play.templates.Template.render(
        at play.mvc.Router.parse(
        at play.mvc.Router.parse(
        at play.mvc.Router.load(
        at play.mvc.Router.detectChanges(
        at play.Play.detectChanges(
        at play.Invoker$Invocation.init(
        at Invocation.HTTP Request(Play!)

So, I then tried reverting the changes in Security and Admin classes
but the last error still happens.

Please advise.


Re: Integrating with LDAP grandfatha 4/1/10 1:30 AM
Did you activate the security module in your application
configuration? If not, that could be a reason why Play does not put
the Secure.Security class on the classpath which is why the
compilation would fail then.

But in general, I think that the following is incorrect:

" User.find("byEmail", Security.connected()).first(); "

You need to replace that with your actual Ldap-Searcher-Class, because
this line will hit the database and not your LDAP server. You can
create an instance of that class in your Security controller yourself
or use dependency injection for that, so you would end up with
something similar to the following:

String username = ...
String password = ...
MyLdapSearcher ldap = new MyLdapSearcher();

User u =, password);

Re: Integrating with LDAP hyder 4/7/10 2:10 AM

Thanks for your advice. It was really helpful.

I'm now able to authenticate against LDAP (tested against Apache DS).
I used the Spring Module and Spring LDAP.

There are still a few limitations left which I'll try to clear and
then I hope I can contribute a write up.


Re: Integrating with LDAP Prakash Agarwalla 3/12/13 10:01 AM
Hi.. I need a working sample of LDAP integration with play framework Version 2. Any one can help ??

Thanks in advance,
Re: Integrating with LDAP Sascha Kleiber 3/13/13 12:56 AM
Yes. You should get the Spring LDAP-Plugin first ( Then you have to create an AttributeMapper depending on the values you want to get from LDAP. I wanted to get user-data from ldap, so I created an "PersonAttributeMapper":

package ldap;

import javax.naming.NamingException;
import ldap.domain.Person;
import org.springframework.ldap.core.AttributesMapper;

 * AttributeMapper for LDAP-mapping (Java Class Person <-> LDAP objectType = person)
public class PersonAttributeMapper implements AttributesMapper {

    public Object mapFromAttributes(Attributes attrs) throws NamingException {
        Person person = new Person();

        return person;

Also you have to create a Mapper-Class which represents an Ldap-Object a a Java-Entity,almost like an ORM-Entity, in my case "":

package ldap.domain;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

 * Mapping class for LDAP-person object
public class Person {

   private String unit;
   private String firstName;
   private String lastName;
   private String email;
   private String username;
   private int ldapid;

    public String getEmail() {
        return email;

    public void setEmail(String email) { = email;

    public String getFirstName() {
        return firstName;

    public void setFirstName(String firstName) {
        this.firstName = firstName;

    public String getLastName() {
        return lastName;

    public void setLastName(String lastName) {
        this.lastName = lastName;

    public String getUnit() {
        return unit;

    public void setUnit(String unit) {
        this.unit = unit;

    public String getUsername() {
        return username;

    public void setUsername(String username) {
        this.username = username;

    public int getLdapid() {
        return ldapid;

    public void setLdapid(int ldapid) {
        this.ldapid = ldapid;

   public boolean equals(Object obj) {
      return EqualsBuilder.reflectionEquals(this, obj);

   public int hashCode() {
      return HashCodeBuilder.reflectionHashCode(this);

   public String toString() {
      return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);

At last I created a DAO:

package ldap.dao;

import java.util.List;
import ldap.domain.Person;

public interface PersonDao {
    public Person findPersonByUsername(String username);

    public Person findPersonByLdapid(int ldapid);

    public List<Person> getAllPersons();

And its implementation:

package ldap.dao;

import java.util.List;
import javax.inject.Inject;
import ldap.PersonAttributeMapper;
import ldap.domain.Person;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.filter.AndFilter;
import org.springframework.ldap.filter.EqualsFilter;

public class PersonDaoImpl implements PersonDao {

    private LdapTemplate ldapTemplate;

    public LdapTemplate getLdapTemplate() {
        return this.ldapTemplate;

    public void setLdapTemplate(LdapTemplate ldapTemplate) {
        this.ldapTemplate = ldapTemplate;

    public Person findPersonByUsername(String username) {
        AndFilter andFilter = new AndFilter();

        andFilter.and(new EqualsFilter("objectclass", "person"));
        andFilter.and(new EqualsFilter("uid", username));

        return (Person) getLdapTemplate().search("", andFilter.encode(), new PersonAttributeMapper()).get(0);

    public Person findPersonByLdapid(int ldapid) {
        AndFilter andFilter = new AndFilter();

        andFilter.and(new EqualsFilter("objectclass", "person"));
        andFilter.and(new EqualsFilter("uidNumber", ldapid));

        return (Person) getLdapTemplate().search("", andFilter.encode(), new PersonAttributeMapper()).get(0);

    public List getAllPersons() {
        return"", "(&(objectClass=person)(!(uid=vpn_*))(!(uid=_ldap*))(description=*))", new PersonAttributeMapper());

For spring you have to create a config file named application-context.xml in folder "conf":

<?xml version="1.0" encoding="UTF-8"?>


    <bean id="contextSource" class="">
        <property name="url" value="ldap://<INSET LDAP IP>" />
        <property name="base" value="cn=users,dc=halx,dc=example,dc=int" />

    <bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate">
        <constructor-arg ref="contextSource" />

    <bean id="ldapPerson" class="ldap.dao.PersonDaoImpl">
        <property name="ldapTemplate" ref="ldapTemplate" />

That's it, works for me. I needed some time to get it working.
You received this message because you are subscribed to a topic in the Google Groups "play-framework" group.
To unsubscribe from this topic, visit
To unsubscribe from this group and all its topics, send an email to
For more options, visit