Tag Archives: Authentication

How to authenticate against LDAP / Active Directory?

Problem Statement

Given a User Name and Password, you want to authenticate the same against LDAP or Active Directory (AD).

Solution – Using a Java Program

Here’s a simple example:

import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;

public class Main {
 public static void main(String[] args) {

 try {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    //NOTE: Replace with appropriate ldap hostname below
    env.put(Context.PROVIDER_URL, "LDAP://ldaphost:389"); 
    //NOTE: Usually DIGEST-MD5 usually works with Windows Active Directory. If not try 'Simple'
    env.put(Context.SECURITY_AUTHENTICATION, "DIGEST-MD5"); 
    //NOTE: Replace with appropriate username and passwd in next two lines.
    env.put(Context.SECURITY_PRINCIPAL,  "putUsernameHere"); 
    env.put(Context.SECURITY_CREDENTIALS, "putPasswordHere>");   

    DirContext ctx = new InitialDirContext(env);
    ctx.close();
  } 
  catch(NamingException ne) {
    System.out.println("Error authenticating user:");
    System.out.println(ne.getMessage());
    return;
}
    System.out.println("OK, successfully authenticated user");
}