Tag Archives: active directory

Simple Java AD/LDAP Authenticaion Code


There are so much of code and reference available for AD/LDAP integration in Java. I also searched a lot and the below code worked for me.
As a non-java developer I found so interesting while working on some complex java stuff.

 

import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;
public class ADTestNew {
    public static void main(String[] args) {
    try {
        Hashtable env = new Hashtable();

        env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");

        env.put(Context.PROVIDER_URL,"ldap://192.168.100.225:389"); //replace with your server URL/IP

        // This line is optional based on environment. You can try with comment or without comment also.
        env.put(Context.SECURITY_AUTHENTICATION,"DIGEST-MD5"); //No other SALS worked with me

        env.put(Context.SECURITY_PRINCIPAL,"login"); // the user name.

        env.put(Context.SECURITY_CREDENTIALS, "Passw0rD"); //the password.

        DirContext ctx = new InitialDirContext(env);

        ctx.close();

    } catch(NamingException ne) {
        System.out.println("Error authenticating user:");
        System.out.println(ne.getMessage());
        return;
    }
    //if no exception, the user is already authenticated.
    System.out.println("OK, successfully authenticating user");
    }
}

Happy Java.