I'd like to test if a given user and password of a LDAP user are correct.
I sorted out that jndi is the library to use.
I found this simple class:
package myldap;
import java.util.Hashtable;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
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;
// boolean function to test user and pwd
public static boolean userVerify(String user, String password){
boolean userVerify = false;
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://192.168.48.10");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "CN=" + user + ",conn");
env.put(Context.SECURITY_CREDENTIALS, password);
try {
DirContext authContext = new InitialDirContext(env);
userVerify = true;
authContext.close();
} catch (AuthenticationException authEx) {
//("Authentication Exception!");
userVerify = false;
} catch (NamingException namEx) {
//("Something went wrong!");
userVerify = false;
}
return userVerify;
}
since i am trying to make it work i am playing around with the parameters. The values i put in the function are
INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
PROVIDER_URL, "ldap://192.168.48.10");
SECURITY_AUTHENTICATION, "simple");
SECURITY_PRINCIPAL, "CN=" + user + ",conn");
SECURITY_CREDENTIALS, password);
with the above i get AuthenticationException, that is the best result i could achieve, by changing things I obtain NamingException, so it seems i am less close to the solution.
In particular i am not sure about SECURITY_PRINCIPAL.
Does anyone have experience and can give advice on how to pass those values correctly pinpointing which ones are wrong? Of course I would like to connect and not raise exceptions.