tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > LDAP > How to Authenticate LDAP User

How to Authenticate LDAP User 

LDAP (Lightweight Directory Access Protocol) is based on X.500 standard. Its a hierarchical data structure with Entries organized in a tree like structure called Directory Information Tree (DIT). The following example shows authenticating a user by logging in as root user. The password string that has to be sent from client side may vary depending on the LDAP Server password encryption strategy. As password encryption strategy is forbidden from normal users, it is better to use direct login with specified user credentials by providing un-encrypted password. The LDAP Server takes care of comparing the encrypted passwords.


File Name  :  
Author  :  Sudhakar KV
Email  :  [email protected]
package com.bethecoder.tutorials.ldap;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;

public class AuthenticateUserTest {

   @param args
  public static void main(String[] args) {

    //Setup the environment to login as 'Directory Manager'
    String rootDN = "cn=Directory Manager";
    String rootPWD = "abcd1234";
    Hashtable<String, String> environment = new Hashtable<String, String>();
    environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environment.put(Context.PROVIDER_URL, "ldap://localhost:389/dc=test,dc=com");
    environment.put(Context.SECURITY_AUTHENTICATION, "simple");
    environment.put(Context.SECURITY_PRINCIPAL, rootDN);
    environment.put(Context.SECURITY_CREDENTIALS, rootPWD);

    DirContext dirContext = null;
    NamingEnumeration<?> results = null;
    try {
      dirContext = new InitialDirContext(environment);
      SearchControls controls = new SearchControls();

      String userId = "sram";
      //May vary based on LDAP Server password encryption strategy
      //String userpwd = "{SSHA}/lLva45c4mgI9ByQrRfowy+ZHiqHGyt0FUZTLw=="; 
      String userPwd = "abcd1234";

      String filter = "(&(objectclass=person)(uid=" + userId + ")(userPassword=" + userPwd + "))";
      results ="", filter, controls);

      if (results.hasMore()) {
        System.out.println("User found");
      else {
        System.out.println("User not found");

    catch (NamingException e) {
    finally {
      if (results != null) {
        try {
        catch (Exception e) {

      if (dirContext != null) {
        try {
        catch (Exception e) {


It gives the following output,
User found


bl  br