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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: