How to connect to LDAP server using Java naming and directory interface(JNDI)

Hello Friends,

In this tutorial,we will see how to connect to LDAP server using JDK's standard Java naming and directory interface(JNDI).

public class LdapService  {
 private static final String INITIAL_CONTEXT_FACTORY = "java.naming.factory.initial";
  /* provider url*/
 public static final String PROVIDER_URL = "java.naming.provider.url";
 
 /*Security Authentication*/
 public static final String SECURITY_AUTHENTICATION = "java.naming.security.authentication";
 
 /*Security Principal*/
 public static final String SECURITY_PRINCIPAL = "java.naming.security.principal";
 
 /*Security credentials*/
 public static final String SECURITY_CREDENTIALS = "java.naming.security.credentials";
 
 /*ldap version*/
 public static final String LDAP_VERSION =  "java.naming.ldap.version";
 
 /*base dn*/
 public static final String BASE_DN = "ou=subjects,o=ed";
 
 /**nameSpaceBinding*/
 @Autowired
 private NameSpaceBinding nameSpaceBinding;
 
 /**ATTRIBUTE_IDS */
 private static final String[] ATTRIBUTE_IDS = { "firstName","surname","mobileNumber","departmentNumber","departmentName" };
 
 /**
  * @param env
  * @param user
  * @throws NamingException
  */
 public User fetchDataByUserId() {
  try{
  Hashtable<String,String> env = setLdapConfigurationData();
  DirContext ctx  = new InitialDirContext(env);
  SearchControls ctls = new SearchControls();
  
  // Specify the attribute list to be returned
  ctls.setReturningAttributes(ATTRIBUTE_IDS);
  ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
   
     // Specify the search filter to match
    String  filter = "(&(objectClass=User)(idmUID="gaurav123"))";
   
     // Search the subtree for objects using the given filter
     // Search the subtree for objects using the given filter
    NamingEnumeration<SearchResult> results = ctx.search(CsaConstants.BASE_DN, filter, ctls);
    if (results != null) {
 iterateResults(results,user);
    }
}catch(CommunicationException communicationException){ System.out.println("Error communicating with Ldap server "); }catch(NamingException namingException){ System.out.println("Error while doing JNDI look up"); } }

/**
 * @param results
 * @param user
 * @throws NamingException 
 */
 private void iterateResults(NamingEnumeration<SearchResult> results,User user) throws NamingException{
 while (results.hasMoreElements()) {
  SearchResult sr = (SearchResult) results.next();
  Attributes attrs = sr.getAttributes();
  if (attrs != null) {
   // we have some attributes for this object
   NamingEnumeration ae = attrs.getAll();
   while (ae.hasMoreElements()) {
    setAttributeInUser(ae, user);
   }
  }
 }
}

/**
  * This method sets attribute values in User object.
  *
  * @param ae
  * @param user
  * @throws NamingException
  */
 private void  setAttributeInUser(NamingEnumeration ae,User user) throws NamingException{
 Attribute attr = (Attribute)ae.next();
        String attrId = attr.getID();
        switch (attrId){
         case "firstName" :
          user.setFirstName((String)attr.get());
          break;
        case "surName" :
          user.setSurName((String)attr.get());
          break;
        case "mobileNumber" :
                 user.setMobileNumber((String)attr.get());
                 break;
         case "departmentNumber" :
         user.setDepartmentNumber((String)attr.get());
         break;
         case "departmentName" :
         user.setDepartmentName((String)attr.get());
         break;
        default :
          System.out.println("In default section");
        }
     }

 /**
  * This method adds Ldap configuration data in Hash table.
  * @throws NamingException
  */
 private Hashtable<String,String>  setLdapConfigurationData() throws NamingException{
  Hashtable<String,String> env = new Hashtable<String,String>();
  env.put(INITIAL_CONTEXT_FACTORY,nameSpaceBinding.getProperty(INITIAL_CONTEXT_FACTORY));
  env.put(PROVIDER_URL,nameSpaceBinding.getProperty(PROVIDER_URL));
  env.put(SECURITY_AUTHENTICATION,nameSpaceBinding.getProperty(SECURITY_AUTHENTICATION));
  env.put(SECURITY_PRINCIPAL,nameSpaceBinding.getProperty(SECURITY_PRINCIPAL));
  env.put(SECURITY_CREDENTIALS,nameSpaceBinding.getProperty(SECURITY_CREDENTIALS));
  env.put(LDAP_VERSION, nameSpaceBinding.getProperty(LDAP_VERSION));
  return env;
 }

}

NamespaceBinding Class

public class NameSpaceBinding {
 /**nsbContext */
 private final Context nsbContext;

    /**
     * @throws NamingException
     */
    public NameSpaceBinding() throws NamingException {
     nsbContext = getNsbContext();
    }

    /**
     * @return
     * @throws NamingException
     */
    public String getEnvironment() throws NamingException {
     return getProperty("environment");
    }

    /**
     * @return
     * @throws NamingException
     */
    private static Context getNsbContext() throws NamingException {
        final String nodeName = (String) new InitialContext().lookup("thisNode/nodename");
        final String serverName = (String) new InitialContext().lookup("servername");
        final String serverScopePrefix = String.format("cell/nodes/%s/servers/%s", nodeName, serverName);
        return (Context) new InitialContext().lookup(serverScopePrefix);
    }

    /**
     * @param name
     * @return
     * @throws NamingException
     */
    public String getProperty(final String name) throws NamingException {
        return (String) nsbContext.lookup(name);
    }

}

User Class

public class User {
 
 /** First name of user */
 private String firstName;
 
 /**surname */
 private String surName;

    /**mobile Number*/
 private String mobileNumber;
 
 /** departmentNumber */
 private String departmentNumber;
 
 /**Department Name */
 private String departmentName;
   
 /**
  * @return the firstName
  */
 public String getFirstName() {
  return firstName;
 }

 /**
  * @param firstName the firstName to set
  */
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 /**
  * @return the departmentNumber
  */
 public String getDepartmentNumber() {
  return departmentNumber;
 }

 /**
  * @param departmentNumber the departmentNumber to set
  */
 public void setDepartmentNumber(String departmentNumber) {
  this.departmentNumber = departmentNumber;
 }

 /**
  * @return the departmentName
  */
 public String getDepartmentName() {
  return departmentName;
 }

 /**
  * @param departmentName the departmentName to set
  */
 public void setDepartmentName(String departmentName) {
  this.departmentName = departmentName;
 }

 /**
  * @return the mobileNumber
  */
 public String getMobileNumber() {
  return mobileNumber;
 }

 /**
  * @param mobileNumber the mobileNumber to set
  */
 public void setMobileNumber(String mobileNumber) {
  this.mobileNumber = mobileNumber;
 }

 /**
  * @return the surName
  */
 public String getSurName() {
  return surName;
 }

 /**
  * @param surName the surName to set
  */
 public void setSurName(String surName) {
  this.surName = surName;
 }
 
}

Name Space binding configuration in WebSphere 

1) Open admin Console of WebSphere and go to Enviorenment->Naming


2) Click on Name space bindings


3) We can add all configurations which we are picking using NameSpaceBinding class in setLdapConfigurationData method as name-value pair.

For that

3.1 Click on New...
3.2 Select binding type as String
3.3 Binding identifier can be any id for that specific property.Example : java.naming.factory.initial-st
3.4 Name should be name of property .Example : java.naming.factory.initial
3.5 String value should be value of property.Example : com.sun.jndi.ldap.LdapCtxFactory

Similarly all properties can be added here.

Advantage of Configuring LDAP connectivity specific configuration  in WebSphere and accessing through JNDI lookup 

By configuring LDAP connectivity specific settings in WebSphere,we are making sure that we don't have dependency on environment in our code,so the same code will run fine on all environments viz. ST,ET,Prod.Only thing which we need to do is configure environment specific setting on webSphere installed on different environments.

So with this,we saw how to connect to LDAP server using Java naming and directory interface(JNDI).Please let me know,if you face any issue while implementing above code.

Thanks for reading.