title: Spring security ldap connection management
body: <p>I am using spring security to authenticate users logging into a webapp. Authentication is currently done with ldap.</p>
  
  <p>Between my webapp and my ldap server lies a firewall. After 50 minutes of inactivity, the firewall flushes idle ldap connections.</p>
  
  <p>Spring security sometimes reuses existing connections, but not always. If it picks a connection closed by my firewall, the login will fail. </p>
  
  <p>The exception I find in my Tomcat log is the following.</p>
  
  <pre><code>org.springframework.ldap.ServiceUnavailableException: ldap:389; socket closed; nested exception is javax.naming.ServiceUnavailableException
  </code></pre>
  
  <p>More specifically, connections causing issues are the ones used for search requests. They're not systematically closed by the framework. Bind requests are always made on a new connection that's closed at the end of the request.</p>
  
  <p>In my app a search request is issued after a bind because of a custom LdapAuthoritiesPopulator granting access only to users with particular roles. I have verified the default LdapAuthoritiesPopulator issues search requests in the same manner.</p>
  
  <p>Is it normal for search request connections to stay open almost indefinitely?
  If it is, is there a way I can change the way spring security manages its connections?</p>
  
  <p>I'm also interested to know if there is a better way than using a custom LdapAuthoritiesPopulator to enforce a role constraint during authentication.</p>
  
  <p>My problem persists after trying easy upgrades:</p>
  
  <ul>
  <li>spring-security 3.1.7 (up from 3.1.2) </li>
  <li>spring-ldap-core 2.0.2 (up from 1.3.0) </li>
  <li>spring-ldap 1.3.1 (up from 1.3.0)</li>
  </ul>
  
  <p>Thanks.</p>