This example shows how to authenticate a LDAP user using Java.
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
class LdapAuthenticator {
public static void main(String[] args) {
String ldapDomain = args[0];
String ldapHost = args[1];
String ldapSearchbase = args[2];
String userName = args[3];
String password = args[4];
String url = ldapHost.endsWith("/") ? ldapHost + ldapSearchbase : ldapHost + "/" + ldapSearchbase;
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, userName + "@" + ldapDomain);
env.put(Context.SECURITY_CREDENTIALS, password);
LdapContext context = null;
try {
context = new InitialLdapContext(env, null);
System.out.println("LDAP authenication succeed for user: " + userName);
} catch (NamingException e) {
System.out.println("LDAP authenication failed for user: " + userName);
System.out.println(e.getMessage());
} finally {
if(context != null) {
try {
context.close();
} catch (NamingException e) {
throw new RuntimeException(e);
}
}
}
}
}
No comments:
Post a Comment