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.*;

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'
    //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);
  catch(NamingException ne) {
    System.out.println("Error authenticating user:");
    System.out.println("OK, successfully authenticated user");

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: