Oct 27, 2012

LDAP Authentication Using Java (JNDI)

LDAP Authentication Using  Java(JNDI)

For authenticating any user with credentials from Active Directory , we can use LDAP (Lightweight Directory Access Protocol).
Below is a simple Java class which contains authenticateUser() method which can be invoked and the user can be authenticated with Active Directory.


import java.util.Enumeration;
import java.util.Hashtable;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
public class LdapProvider {

   private static final String auth_method  = "simple";
     // set the LDAP client Version
   private static final String ldap_version = "3";
     // This is our LDAP Server's IP
   private static final String ldap_host    = "10.10.10.10"; //change this as per yours     // This is our LDAP Server's Port
   private static final String ldap_port    = "389";
  
     // This is our base DN
   private static final String base_dn      = "DC=exchange2k7,DC=com"; // //change this as per yours 
   public boolean authenticateUser(String userId,String password){
   
     boolean isValidUser = false;
     String ldap_dn      = "cn="+userId+",cn=Users,"+ base_dn ;
   
     DirContext ctx      = null;
      Hashtable<String, String> env       = new Hashtable<String, String>();
      // Here we store the returned LDAP object data
      String dn = "";
      // This will hold the returned attribute list
      Attributes attrs;
      env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
      env.put(Context.PROVIDER_URL,"ldap://" + ldap_host + ":" + ldap_port);
      env.put(Context.SECURITY_AUTHENTICATION, auth_method);
      env.put(Context.SECURITY_PRINCIPAL, ldap_dn);
      env.put(Context.SECURITY_CREDENTIALS, password);
      env.put("java.naming.ldap.version", ldap_version); 
     
    try{
        System.out.println("Connecting to host " + ldap_host + " at port " + ldap_port + "...");
        System.out.println();
        ctx = new InitialDirContext(env);
        System.out.println("LDAP authentication successful!");
        // Specify the attribute list to be returned
         String[] attrIDs = { "memberOf" };
        SearchControls ctls = new SearchControls();
        ctls.setReturningAttributes(attrIDs);
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        // Specify the search filter to match
        String filter = "(&(objectClass=user)(sAMAccountName="+userId+"))";
        // Search the subtree for objects using the given filter
        NamingEnumeration<SearchResult> answer = ctx.search(base_dn, filter, ctls);
        // Print the answer
        //Search.printSearchEnumeration(answer);
        while (answer.hasMoreElements()) {
       isValidUser = true;
          SearchResult sr = (SearchResult)answer.next();
          dn = sr.getName();
          attrs = sr.getAttributes();
          System.out.println("Found Object: " + dn + "," + base_dn);
          if (attrs != null) {
            // we have some attributes for this object
            NamingEnumeration ae = attrs.getAll();
            while (ae.hasMoreElements()) {
              Attribute attr = (Attribute)ae.next();
              String attrId = attr.getID();
              System.out.println("Found Attribute: " + attrId);
              Enumeration vals = attr.getAll();
              while (vals.hasMoreElements()) {
                String attr_val = (String)vals.nextElement();
               System.out.println(attrId + ": " + attr_val);
              }
            }
          }
       }
        // Close the context when we're done
        ctx.close();
      } catch (AuthenticationException authEx) {
        authEx.printStackTrace();
        System.out.println("LDAP authentication failed!");
      } catch (NamingException namEx) {
        System.out.println("LDAP connection failed!");
        namEx.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
     }
      return isValidUser;
   }
}


Above class can directly be used and authenticateUser() method can be invoked after creating an instance of LdapProvider class.

Feel free to contact me in case getting any issues.

No comments:

Post a Comment