Simple Authentication Using Spring LDAP

It’s with great pleasure that we can now finally announce the final 1.3.0 version of Spring LDAP. It’s been a while since we’ve made a major release, but there’s quite a bit in this one to make up for it. Among the highlights of this release are the improvements in the authentication area, which is the intended focus of this post.

Simple LDAP Authentication

One of the most requested pieces of functionality in Spring LDAP has been a means to perform simple authentication. We have previously hesitated to include this, not finding any logical place to put it. In this release however we got a couple of suggestions on suitable API additions that enabled us to attack this from a different angle, in the end resulting in explicit methods in LdapTemplate for this purpose.

Background

The problem with authentication in LDAP is that it normally requires two separate steps: First you need to find the principal to authenticate in the LDAP tree, typically performing an LDAP search based on e.g. a user name. A new LDAP connection will then be acquired, authenticating it using the Distinguished Name of the found entry (normally referred to as an ‘LDAP Bind’).

Example

Consider the LDAP tree below:
Ldap Tree
Let us say a user identifying himself as ‘John Doe’ is trying to log into our system. We would execute a search from the top of the LDAP tree using a search filter like (&(objectclass=person)(cn=John Doe)). The search would return one single entry, from which we would extract the absolute DN; cn=John Doe, ou=company1, c=Sweden, dc=jayway, dc=se. This DN would then be used for authenticating a new LDAP connection to the server, thus validating the password supplied by the user.

New Spring LDAP Authentication API

While the above has indeed been possible to do using previous versions of Spring LDAP, it has required quite a lot of work and resulted in rather messy code. Spring LDAP 1.3.0 adds a couple of methods to LdapTemplate, making the authentication procedure very straightforward:

The first method performs exactly the procedure described above, returning true or false depending on the outcome. The second method goes one step further, allowing us to perform any operation on the authenticated LDAP connection. Focusing on the simplest case, a standard authentication method using Spring LDAP would look something like the following:

Simple, clean and to the point, especially compared to the mess that used to be required (won’t linger on those nasty details here). Obviously however, using a Spring library we will be required to write a few lines of XML as well:

A couple of comments on the suggested solution:

  • The search needs to return exactly one result entry. In the example above, if there would be more than one person entry in the tree with cn ‘John Doe’ (which would be perfectly legal according to schema regulations), the call to authenticate would fail.
  • In actual implementations the attribute to use for identification will likely be e.g. uid or sAMAccountname (in Active Directory). Both of these attributes have uniqueness enforced throughout the entire tree by the LDAP server.
  • The method only returns true or false; thus the actual reason for failing will not be visible to the caller. The reason will however be logged, which might be useful useful when tracking down problems with search filters and such.
  • A common reason for confusion in LDAP searches is the base parameter, which is used for pointing out where in the LDAP tree to start searching. Referring again to the potential problem where several users might have the same cn; in that case these entries would have to be located in different subtrees. The search could then be narrowed by specifying a different base DN to the authenticate method, e.g. c=Sweden, dc=jayway, dc=com

Note: While the provided methods will handle the simple task of authentication for you it is likely that your actual security requirements go way past plain authentication (e.g. authorization, web integration, etc.). The realm of security is a very complex one, which is the reason you should carefully consider your actual requirements – if they appear to go beyond simple authentication you should definitely consider using Spring Security instead. (Obviously, under the covers Spring LDAP would be used for the actual authentication anyway).

That said, for many systems the API provided with Spring LDAP will be quite sufficient.

Other improvements in Spring LDAP 1.3.0

As compared to the 1.2.1 version of Spring LDAP, 1.3.0 includes more than 50 fixes, varying from internal modifications and minor improvements to important bug fixes and significant functionality additions. The full list of modifications can be viewed in the the changelog.

About Spring LDAP

Spring LDAP is a Java library for simplifying LDAP operations, based on the pattern of Spring’s JdbcTemplate. The framework relieves the user of common chores, such as looking up and closing contexts, looping through results, encoding/decoding values and filters, and more. The library is free, open source, and distributed under the Apache Licence version 2.

For more information on the Spring LDAP project, including downloads, maven usage, as well as project reference and API documentation, refer to its project home page on springsource.org. Support and enhancement requests will be answered in the Spring LDAP Forum at Spring Community Forums.

This Post Has 55 Comments

  1. LDAP authentication is an important feature, I think that this project has reached an important goal!

    Great!

    In previous versions you had to implement a method (can I call it as an “expoloit”? :-P) to make an LDAP authentication feature.

  2. This is wonderful, a lot cleaner.

    But I think you have a typo in the login method, the constant name is EMPTY_PATH instead of EMPTY_NAME.

    Thanks,

    David Cifuentes

  3. Quite right. Fixing that right away, thanks.

  4. i’d like to use custom field to store password – is it possible to set up ldapTemplate somehow?
    thx!
    bcs

    1. I’m afraid I don’t quite understand what you mean. Could you be a little more specific?

  5. :) sorry.
    I suppose, ldapTemplate.authenticate try to read the password from the attribute called ‘userPassword’…
    I have a custom schema – if I will use this new feature (ldapTemplate.authenticate) probably must have a field called that, or is it possible configure where (in which property) can it be found (setPasswordAttribute, or whatever)

    bcs

  6. Ah, I see what you mean. The good news is that this is irrelevant – LdapTemplate makes no assumption regarding which attribute is used for storing the password. What happens is that we will try to do an LDAP ‘bind’ (i.e. connect) to the target server using the found user’s DN and the supplied password. The LDAP server will then internally determine how to match the supplied information – the actual password attribute will hence be out of the control of Spring LDAP.

    Now, this is the standard way of authenticating using LDAP. Another way (not as commonly used) is to manually match a supplied password against a particular attribute. This is NOT what the LdapTemplate#authenticate methods are intendended to do – if you need to do this you’ll have to do it yourself (e.g. using search filters).

  7. thank you! i’ll solve my problem in ldap side…

  8. Hey.. thanks for such a good article. I tried implementing ur approach and never had a luck to make it work.

    Here is the error that i received
    [java] org.springframework.ldap.AuthenticationException: [LDAP: error code 49 – NDS error: failed authentication (-669)]; nested exception is javax.naming.AuthenticationException: [LDAP: error code 49 – NDS error: failed authentication (-669)]
    [java] at org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:180)
    [java] at org.springframework.ldap.core.support.AbstractContextSource.createContext(AbstractContextSource.java:266)
    [java] at org.springframework.ldap.core.support.AbstractContextSource.getContext(AbstractContextSource.java:106)
    [java] at org.springframework.ldap.core.support.AbstractContextSource.getReadOnlyContext(AbstractContextSource.java:125)
    [java] at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:287)
    [java] at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:237)
    [java] at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:624)
    [java] at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:535)
    [java] at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:462)
    [java] at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:483)
    [java] at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:503)
    [java] at org.springframework.ldap.core.LdapTemplate.authenticate(LdapTemplate.java:1424)
    [java] at org.springframework.ldap.core.LdapTemplate.authenticate(LdapTemplate.java:1386)
    [java] at com.anf.chr.flex.service.impl.TestSpring.login(TestSpring.java:44)
    [java] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    [java] at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    [java] at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    [java] at java.lang.reflect.Method.invoke(Unknown Source)
    [java] at flex.messaging.services.remoting.adapters.JavaAdapter.invoke(JavaAdapter.java:421)
    [java] at flex.messaging.services.RemotingService.serviceMessage(Rem

    Configuration:

  9. Ah, this might be a little bit tricky to understand. The AuthenticationException you’re getting happens when performing the search for the user. As I mention in the blog post the authentication procedure happens in two steps: first the DN of the user to authenticate must be found, then that DN is used for authenticating the user.

    Now, the LDAP server will most likely need the system to authenticate in order to perform the search, which is why you’ll need to provide a system user DN and password in your ContextSource configuration. Your exception indicates you’ve configured an invalid DN or password for the system user.

  10. Thanks a lot for the article, but
    the failing reason during authentication will only be logged, is there a way to get it back to the caller?

  11. I had the same problem as in # 10, but I understand what you are saying in comment # 11.

    My problem is I am able to search for a USer and I got the userdn back, now, how can I use that dn for authentication?

    If i supply that in authenticate(dn,..,..), I get LDAP: error code 32 – 0000208D:

    Thanks!

  12. I have a question.

    I have successfully used this new way of authenticating using Spring LDAP ldapTemplate.authenticate(userId, password), and it works great. However, I was wondering if it would be more performant to use a PoolingContextSource.

    After I added the PoolingContextSource, I was happily greeted with a UnsupportedOperationException. This is because the getContext(principal, credentials) is not supported. So does this mean that it would not be beneficial to pool LDAP connections when using this new api method? If it would be beneficial from a performance standpoint, to pool the connections, could you offer some advice on how to go about doing that?

    Thanks in advance for any help you are able to contribute.

  13. There’s actually a very simple explanation for this. In order to authenticate the user the ContextSource will perform an LDAP ‘bind’ operation, which means creating a new connection to the server using the specified user DN and password. This obviously means that these connections cannot be pooled.

    Now, this is one of the use cases that LDAP is specifically designed for; LDAP connections are very lightweight, so you should be all right anyway.

  14. Thanks Mattias….that pretty much explains it ;)

  15. Hi,
    My LDif file contains uid and userPassword as attributes. I want to authenticate the user using this two fields. I tried using ldap search but it fails. Maybe because when i print the value for the attribute userPassword its something non-sense. Maybe because its encrypted. So if i wanna authenticate a user using this 2 fields how should i proceed? I am beginner in this section and trying it for last 2 days. AnyHelp will be appreciated. please

  16. When using the “authenticate” method, is there a way to obtain the reason for the AuthenticationException, rather than just “false”?

    I really need those error codes.
    Are they mapped elsewhere?

    Thanks!
    -Larry

  17. Agree with Larry there should be a way (exception?) to get the error code instead of just false. Meanwhile, is there any workaround for getting the error code?

    Thanks,

    David Cifuentes
    Eforcers.com

  18. I am having touble with the authentication for a user.
    1) I login to the Ldap with the principal credentials. This is ok, and I have permissions to do subsequent searches

    2) I then can correctly authenticate a user with the correct password.

    3) However, if I present an incorrect password, I get the following:

    org.springframework.beans.factory.xml.XmlBeanFactory@c4bc34: defining beans [contextSource,ldapTemplate,ldapService]; root of factory hierarchy

    2010-02-16 13:09:44,530 [main] ERROR org.springframework.ldap.core.LdapTemplate – Authentication failed for entry with DN ‘cn=43530801,ou=HSBCPeople,dc=InfoDir,dc=Dev,dc=HSBC’
    org.springframework.ldap.AuthenticationException: [LDAP: error code 49 – 8009030C: LdapErr: DSID-0C090336, comment: AcceptSecurityContext error, data 52e, vece

    Here is the key piece of code:

    public boolean loginByCn(Person p, String password) throws AuthenticationException
    {
    AndFilter filter = new AndFilter();
    OrFilter orFilter = new OrFilter();
    orFilter.or(new EqualsFilter(“objectclass”, “user”))
    .or(new EqualsFilter(“objectclass”, “userproxy”));

    filter.and(orFilter).and(new EqualsFilter(“cn”, p.getCn()));
    return ldapTemplate.authenticate(DistinguishedName.EMPTY_PATH, filter.toString(), password);
    }

    The p.getCn() becomes “43530801” and is correct. The password is purposely set to be incorrect, as “xyz”.

    any suggestions ?

  19. Hi, can you help with the password policy?
    I am developing a webservice for authenticating the user in LDAP, but I have no idea about how to get the message from Password Policy after authentication.

    I heard that I can use DirContextProccessor to get the message, but in implementing the AbstractRequestControlDirContextProcessor class, I don’t know which Control to use and how to use the class I implemented.

    Any tips will be highly appreciated, thanks very much.

  20. Hi,

    I used your code to login into our application.
    Every thing is working fine if search returns 1 result.

    I think you might change your code little bit.
    If you find more than 1 user you returning back there itself.
    But you are not trying to bind it. There might chance of only one result/username can bind with the given credentials.

    What do you say.
    Sorry for my english

    Thanks and Regards
    RS

    1. I hope I’m understanding you correctly here, if not please feel free to comment back.

      If the search returns more than 1 result the authentication is considered failed – there is simply no way for for the system to know which one of the hits to use for authentication. Should the first one be used? Why not the second one? The point here is that the user principal (the name the user identifies himself with) must be unambiguous, or else we don’t know who we’re authenticating.

      Bottom line: you need to make sure the user name is unique, or limit your search to make sure that it only returns a single result.

  21. There’s been quite a bit of requests here on getting information on the actual authentication failure, e.g. the root authentication exception. We have given some thought to this criticism, and there’s been work done in trunk to make it work.

  22. Great article.

    I’ve few question though :)

    I’m using spring-ldap-1.2.1 which doesn’t provide authenticate() method..:(.

    In order to authenticate user, First – I do a search based on sAMAccount and then retrives users DN.

    Now how can I authenticate user using the resulted DN? what is the correct way to bind user?

    I didn’t get any method in LdapTemplate class that binds(authenticates) user.

    Shall I compare user’s sAMAccount and userPassword field, like the sql way?? (doesn’t look good to me)

    Thanx,
    Mayank

  23. You really should upgrade to 1.3; the 1.2.1 version is really, really old.

    If for any reason that would be impossible to do, the code is freely available, so there shouldn’t be any problem to just copy this code from the 1.3 version and plug it into your project.

  24. Hi Mattias,
    Thanks for the great post. I couldn’t get it working for some reason though. I have ApacheDS installed with the following entry:

    dn: cn=Tulsi Rai,ou=people,o=sevenSeas
    objectclass: person
    objectclass: organizationalPerson
    objectclass: inetOrgPerson
    objectclass: top
    cn: Tulsi Rai
    description: Software Developer Tulsi Rai
    givenname: Tulsi
    sn: Rai
    uid: trai
    userpassword: {SHA}lQ5FtsMcintJGvpkCbcTCUYlfLc=

    Here’re my codes for authentication:

    public boolean login(String username, String password) {
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter(“objectclass”, “person”)).and(new EqualsFilter(“uid”, username));
    System.out.println(filter.toString());
    return ldapTemplate.authenticate(DistinguishedName.EMPTY_PATH, filter.toString(), password);
    }

    And the call is login(“trai”, “pass”);

    Here’s the exception:
    SEVERE: Unable to find unique entry matching in authentication; base: ”; filter: ‘(&(objectclass=person)(uid=trai))’. Found 0 matching entries

    I don’t have any clue as to why it can’t find “trai” as an uid. I would appreciate if you could give a pointer or two as to the contributing factors to this problem.
    Thanks.
    TR

  25. Hi,

    I have a question, thanks in advance for your response.

    I am using the following code in our java application to autheticate LDAP user with Active Directory using common name:

    // Manual LDAP connection
    String dnStrVal = “CN=username,CN=Users,DC=company,DC=local”;
    LdapContextSource ctxSource = new LdapContextSource();
    ctxSource.setUrl(ldapUrl);
    ctxSource.setUserDn(dnStrVal);
    ctxSource.setPassword(password);
    ctxSource.setPooled(false);
    ctxSource.afterPropertiesSet();
    ctxSource.getReadWriteContext();

    I need to authenticate using sAMAccountName. I think that first I would need to do a search and get the DistinguishedName using sAMAccountName and then use the same code logic that I have above to do the authentication.

    I have started playing with LDAP. Can you please let me know how to do a search using sAMAccountName and get the DistinguishedName value? I am not using any xml files or any other LDAP files. I just have the above code in my java application and the Spring LDAP jar files in the classpath.

    Thanks,
    Snehal.

  26. Hi there.
    I am getting a weird error when configuring ldap

    2010-07-09 11:05:21,476 ERROR [org.springframework.web.context.ContextLoader] –
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘contextSource’ defined in ServletContext resource [/WEB-INF/classes/context/applicationContext-userAdmin.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.apache.commons.lang.ArrayUtils.isEmpty([Ljava/lang/Object;)Z

    i have put details in the forum
    http://forum.springsource.org/showthread.php?t=91932

    Not sure what configurations I am missing.

  27. It would be great to have the full example code.

  28. One comment:
    I do not agree with the assumption that bind can only be done using the DN attribute. In most cases the “double-bind” is not necessary and JNDI allows specifying the user principal attribute. In most AD implementations, users can bind using their sAMAccountName attribute.
    Are there any other implementation options in Spring LDAP? With bind-and-search, we need to expose the admin credentials in a clear-text file, which is not fantastic and most organizations will not accept it.

  29. Hi,
    Seems like it’s a nice blog. So let us also add something useful in it. With all positive manufacturing data scope of import and export is increasing day by day. In mechanical field everyone want to have one stop shop for there manufacturing needs. So Relicaexpo is the ultimate solution for them.

    Regards
    . Relicaexpo

  30. Hi Guys,

    I am facing the same issue with authenticate method on ldapTemplate. I had spring-ldap-1-3.0.Release-all.jar in classpath. But still no luck.
    Any ideas ?

    Thanks,
    Naveen

  31. I have been using 1.2 version and we finally decided to support TLS since 1.3 now provides a way to do this. We have been using ldaptemplate for all the queries. Here is what I have:

    final LdapContextSource context = configureContextSource();
    final SpringSecurityLdapTemplate template =
    new SpringSecurityLdapTemplate( context );

    // Active Directory doesn’t transparently handle referrals. This fixes that.
    template.setIgnorePartialResultException(true);

    // Searching for classSchema since we expect this to be present as a part of all the LDAP Schemas.
    // This should help us confirm that the LDAP connection related params are all fine.
    template.searchForSingleAttributeValues(…..);

    ——————————-
    private LdapContextSource configureContextSource() throws DirectoryServiceConfigurationException {

    MyTlsDirContextAuthenticationStrategy authenticationStrategy =
    new MyTlsDirContextAuthenticationStrategy();

    final String url = buildLdapURL();
    LdapContextSource ctxSrc = new LdapContextSource();
    ctxSrc.setUrl(url);
    ctxSrc.setCacheEnvironmentProperties(false);

    if(!ldapConfig.get(LDAP_USE_ANONYMOUS_BIND).getPreferenceValueBoolean()) {
    ctxSrc.setUserDn(ldapConfig.get(LDAP_BIND_DN).getPreferenceValue());
    ctxSrc.setPassword(ldapConfig.get(LDAP_BIND_PASSWORD).getPreferenceValue());
    }

    ctxSrc.setAuthenticationStrategy(authenticationStrategy);

    try {
    ctxSrc.afterPropertiesSet();
    } catch (final Exception ex) {
    log.error(ErrorCode.LDAP_INIT_SECURITYCONTEXT_FAILED.getCodeString() +
    ErrorCode.LDAP_INIT_SECURITYCONTEXT_FAILED.getDescription(), ex);
    throw new DirectoryServiceConfigurationException(ErrorCode.LDAP_INIT_SECURITYCONTEXT_FAILED.getDescription(),
    ErrorCode.LDAP_INIT_SECURITYCONTEXT_FAILED.getCode());
    }

    return ctxSrc;
    }

    ——————-

    MyTlsDirContextAuthenticationStrategy is extended from DefaultTlsDirContextAuthenticationStrategy only to set the system properties for keystore and other related properties.

    I have a open Ldap server setup to support TLS. Code looks much more clean to me. However, when the template.searchForSingleAttributeValues(…..); is invoked, it complains of TLS already started.

    I drilled down more and found that,

    LdapTemplate.search(……) –> AbstractContextSource.getReadOnlyContext() –> AbstractContextSource.getContext(String principal, String credentials) –> authenticationStrategy.processContextAfterCreation(…)

    will now try to Start TLS again and fails since it is already started and the exception is thrown which results in search failure.

    I am not seeing a way I can bypass this issue since every operation on the LdapTemplate will try to obtain a ReadOnlyContext and will fail at the same place since TLS is already started. I don’t think this will go away since LdapTemplate is very specific to Spring-ldap.

    However, please suggest a workaround if possible or other ideas/suggestions.

  32. On a different note, extending the LdapContextSource in 1.2 to support TLS worked fine in the first instance of starting TLS. However, subsequent changes to the properties or removing the keystore has no effect on the context that was established in the first attempt.

    Seems to me like something is being cached. I tried removing pooling and not caching environment properties, but the issue doesn’t seem to go away. On restarting my server, the issue gets resolved and the new context I obtain behaves as expected.

    Can’t seem to understand what may be going wrong. Suggestions are welcome.

  33. Hi Mattias,

    I have configured baseURL as follows and it works fine for the first step(i.e to retrieve user’s DN)

    Now during authentication when I use “dc=example,dc=com” instead of DistinguishedName.EMPTY_PATH, I get the following exception (ldapTemplate.authenticate(“dc=example,dc=com”, filter.toString(), password);
    ) :

    org.springframework.ldap.NameNotFoundException: [LDAP: error code 32 – 0000208D: NameErr: DSID-031001CD, problem 2001 (NO_OBJECT), data 0, best match of:
    ‘DC=example,DC=com’
    nested exception is javax.naming.NameNotFoundException: [LDAP: error code 32 – 0000208D: NameErr: DSID-031001CD, problem 2001 (NO_OBJECT), data 0, best match of:
    ‘DC=example,DC=com’
    remaining name ‘dc=example,dc=com’
    at org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:172)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:306)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:237)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:624)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:535)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:462)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:483)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:503)
    at org.springframework.ldap.core.LdapTemplate.authenticate(LdapTemplate.java:1424)
    at org.springframework.ldap.core.LdapTemplate.authenticate(LdapTemplate.java:1410)
    at org.springframework.ldap.core.LdapTemplate.authenticate(LdapTemplate.java:1397)

    It works fine when I use DistinguishedName.EMPTY_PATH as a baseURL during authentication –

    return ldapTemplate.authenticate(DistinguishedName.EMPTY_PATH, filter.toString(), password);

    Could you please elaborate how the baseURL is handled during authentication? Why it fails when I use “dc=example,dc=com”?

    Thanks much!,
    Mynk

  34. hi there,
    i an application http://localhost:8080/HelloWorld
    we are using a login based on jspring security checking and a applicationcontex-security.xml file where a set of roles where defined in database(logedin table).A set of roles is defined to access the urls,
    first question
    can i dinamicaly change the roles with out restart the server(glassfish 3).
    second question
    only roles like hasAcess{‘ROLE_ADMIN’,’ROLE_USER`’} can i change the ROLE_ADMIN to 1 ,2 ,3 etc
    other that words(ROLE_ADMIN etc….)
    third question
    there a login status table means which all persons are loged in properly there status will be set to ‘Y’,and we are validating that is that flag is set to y then block that user saying that “you are already LOGED in”,
    but tha problem is if the user didn’t logout properly or IF HE CLOSED THE BROWSER then that flag will not reset to N ,so he can’t logged in.
    how can i get rid of it,
    and how the session management is propery done by spring,
    we are using ldap to store password and there uses SSO
    there session time out between these two

    please give me good solution or good sample blogs

    please help

    thanks in advance

  35. Our project have exactly the similar requirement ( we just need to authenticate the user ) and expect the boolean status in response. I used the code mentioned above but receiving CommunicationException …. as shown below :
    Exception in thread “main” org.springframework.ldap.CommunicationException: XX.XX.XXX.XX:XXXX; nested exception is javax.naming.CommunicationException: 10.47.128.29:3268 [Root exception is java.net.ConnectException: Connection refused]
    at org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:98)

    The configuration set I am using here is :

    1) Spring framework : 2.5.6.SEC01
    2) Spring Ldap : 1.3.1.RELEASE
    3) Java 1.6

    A) Will this spring ldap API compatible to both LDAPv2 and LDAPv3 versions of LDAP server ?
    B) Also do I need to include spring-security ?, I have seen on few blogs the reference of ” …..
    in the applicationContext.xml. Based on the above mentioned description it does not seem to be of any relevance for this requirement but still would like to confirm.

    Thanks in advance.

  36. Found that tag entered in the above comment got omitted, so for spring -security part have found these entries in applicationContext.xml

    beans:bean id=”ldapAuthProvider” class=”org.springframework.security.providers.ldap.LdapAuthenticationProvider

    beans:bean class=”org.springframework.security.providers.ldap.authenticator.BindAuthenticator”

    and the related bean initialization entries.

  37. I am unable to get the response from ldaptemplate it taking long time and even not responding, do i need to enable the port(389) if it is why it shouldn’t ask for port is not enable, i followed the above post properly but couldn’t able please help me out

    Thanks in advance,
    Srinivas

  38. Nice and clean example. I am able to connect to the ldap server but while authenticating the user credential I am getting “false”. Where should I check the log entry for specific error. I am using WebLogic server 10.3 and my code is quick and dirty, I do not have logging implemented. Please help.
    Sam

  39. I’m setting a bind from spring ldap to ADAM repository, it’s works when you use a ADAM account and simple authentication but I need do the bind with a windows account (LSA).

    Could you please help me?

    Added the part of the code:

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY,”com.sun.j ndi.ldap.LdapCtxFactory”);
    env.put(Context.PROVIDER_URL,param.getLdapUrl()); //replace with your server URL/IP
    env.put(Context.SECURITY_AUTHENTICATION,”DIGEST-MD5″);
    env.put(Context.SECURITY_PRINCIPAL,userName); // in format domainusername or username@domain
    env.put(Context.SECURITY_CREDENTIALS, passWord); //the password

    DirContext ctx = new InitialDirContext(env);

    This is raising the next error: error code 49 – 80090308 data 57

  40. I have a case where the CN part of the DN contains double-quotes in the middle of the value. Example: CN=Odin “Viking” Rules,DC=viking,DC=org

    Looks like the construction of DistinguishedName object has errors in it because the debug log shows: CN=Odin ,dc=viking,dc=org

    Subsequent attempt to bind obviously failed and the user cannot login.
    Any advice on how to fix this?
    Thank you in advance.

  41. hi ,
    I Create an spring roo application carpooling in this application i have an login page (Uid,Password) but username and password are in local server so i want to connect my application with serve using LDAP .Please any help

  42. Btw, when supplying empty password, if you expect LdapTemplate.authenticate to return false, or contextSource.getContext(userDn, credentials) to throw exception, beware!

    Documentation should point this out, but it does not.

  43. Hi,
    Thanks for the article:)

    i would like to know if i can search with only username. I need to lookup one user Id in the LDAP and get other information for the User id. please suggest.
    Thanks!

  44. Hi,

    I encounter below exception when I enter a correct username & password. There is no issue when the username & password is not valid.

    Can anyone advise?

    java.lang.NoSuchMethodError: org.apache.commons.lang.StringUtils.replaceEach(Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;)Ljava/lang/String;
    org.springframework.ldap.core.DistinguishedName.unmangleCompositeName(DistinguishedName.java:250)
    org.springframework.ldap.core.DistinguishedName.parse(DistinguishedName.java:217)
    org.springframework.ldap.core.DistinguishedName.(DistinguishedName.java:176)

  45. Hey. I have used the same code. But I have 3 users in my LDAP server.
    at org.springframework.ldap.core.LdapTemplate.authenticate(LdapTemplate.java:1488)
    at org.springframework.ldap.core.LdapTemplate.authenticate(LdapTemplate.java:1385)
    at com.ldap.main.LdapTest.main(LdapTest.java:92)

    I get this error. I am not able to figure out this. Please let me know

Leave a Reply

Close Menu