Tuesday, October 23, 2018

[Java] Lightweight Directory Access Protocol (LDAP) Authentication


Securing an application require some form of user authentication. Most of the time users are contain in database or LDAP to manage logon credentials, i.e. username and password. 

The diagram below shows an application deployed in an application server, e.g. Websphere, JBoss call LDAP to authenticate logon user.



Below is a sample code to authenticate user against LDAP user repository.



import java.util.Hashtable;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class LdapAuthenticationAdapter{

  public boolean authenticate(
    String username, 
    String password){

DirContext context = null;
SearchResult result = null;
String usrNamespace = null;
NamingEnumeration<javax.naming.directory.SearchResult> answers = null;

SearchControls ctrls = new SearchControls();
        ctrls.setReturningAttributes(new String[] { "givenName", "sn","memberOf" });
        
    ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
       
    try{

answers = getDirContext().search("ou=bankfusionusers", "(uid="+username+")", ctrls); // Get directory context
result = answers.nextElement();
usrNamespace = result.getNameInNamespace();
       
     Properties props = new Properties();
     props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
     props.put(Context.PROVIDER_URL, "ldap://manvsweqdv0011:10389/dc=misys,dc=com");
     props.put(Context.SECURITY_PRINCIPAL, usrNamespace);
     props.put(Context.SECURITY_CREDENTIALS, password);
       
     context = new InitialDirContext(props);

  }catch(NamingException e){
      return false;
}catch(NullPointerException e){
return false;
}
       
  return true;

}


public DirContext getDirContext()throws NamingException{
// Get admin user, password(encrypted), host, port and other LDAP parameters
Hashtable<String, Object> env = new Hashtable<String, Object>();
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
env.put(Context.SECURITY_CREDENTIALS, "secret");
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://{hostname}:{ldap_port}/dc={xxxxx},dc=com");
env.put("java.naming.ldap.attributes.binary", "objectSID"); //      validate this line if applicable

return new InitialDirContext(env);

}//end method

}

No comments:

Post a Comment